From c81a00e7ef4eeafbded28ff59e91f109fdb1a63d Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Thu, 26 Nov 2026 16:24:17 +0100 Subject: [PATCH 1/8] Read the GPS of 70mai dashcam clips from the log beside them 70mai dashcams write no GPS into their clips that mapillary_tools or ExifTool can read. They write it to a text log beside the clips instead, GPSData000001.txt, with a row per fix: the Unix time (UTC), the fix status, the position, and the name of the clip being recorded. One log covers many clips and hours. So process and video_process failed these clips with MapillaryVideoGPSNotFoundError. The native reader now falls back to the GPSData*.txt logs in the folder of a video in which no other native reader finds GPS. It takes the valid fixes of the rows that name the clip: status A, a positive time, a finite position that is not null island. The rows name the clip by its file name, matched by its stem, as some cameras leave characters of a longer name after the extension (".MP44"). A log is indexed once per process, by the byte ranges of the rows of each clip: a 60 MB log of 650,000 rows takes 0.3 s, then each clip reads only its own rows. Without a log, the fallback costs a listing of the folder, once per folder. The rows carry the GPS time, not the time in the video. In the middle of a recording, the camera writes the first row of a clip within about a second of its start, so the first fix is taken as video time 0. A camera that is switched on records before it has a fix, which took from 7 seconds to nearly 3 minutes in the logs seen. Then it either writes rows without a fix that name the clip before the first fix, or the fixes span at least 9 seconds less than the clip (a stall of the GPS cost at most 6 seconds otherwise), and the last fix is taken as the end of the clip instead. A clip without a fix at either end, or whose fixes span more than 5 seconds longer than the clip, gets no GPS from the log, as before. As the fallback is in the native reader, the log is used by the default sources of process, by sources that try native before exiftool_runtime, by sample_video for the GPS clock and positions of the frames, and to place a GPX track on the clip by its GPS clock. A GPX converted from the whole log was placed to start with the clip before: 19 and 39 km off for two sample clips. It is placed by the log's clock now. On three sample clips, process geotags them from the log, and upload --dry_run writes their fixes as a CAMM track. For two logs of 60 and 115 clips, the fixes read for every clip are the ones that GPSBabel's 70mai reader converts. video_process places the frames on the track of the log; the position that the camera prints on each frame, which it updates once a second, is the position of 0.6 to 1.5 seconds earlier on that track. --- README.md | 1 + docs/command_reference.md | 2 +- .../geotag/video_extractors/native.py | 31 ++ mapillary_tools/seventymai_log_parser.py | 302 ++++++++++++++++++ tests/unit/test_seventymai_log_parser.py | 288 +++++++++++++++++ 5 files changed, 623 insertions(+), 1 deletion(-) create mode 100644 mapillary_tools/seventymai_log_parser.py create mode 100644 tests/unit/test_seventymai_log_parser.py diff --git a/README.md b/README.md index 8c27fe226..0fef00962 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,7 @@ mapillary_tools supports videos (.mp4, .360) that contain any of the following t - [DR900S-1CH](https://shop.blackvue.com/product/dr900x-1ch-plus/) - [DR900X Plus](https://shop.blackvue.com/product/dr900x-2ch-plus/) - Novatek-based dashcams, such as Viofo, Vantrue and Anker Roav dashcams +- 70mai dashcams, from the GPS log (`GPSData000001.txt`) that they write beside the videos: keep it in the same folder Other videos can be geotagged from the GPS that [ExifTool](https://exiftool.org/) reads, if it is installed, or from a GPX or NMEA track recorded along with them (see [Geotagging with GPX](#geotagging-with-gpx)). diff --git a/docs/command_reference.md b/docs/command_reference.md index 97fc21e8c..c7a96039c 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -215,7 +215,7 @@ Repeat the option or separate sources with commas. The default is `native`, then | Source | Images | Videos | | ------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------ | -| `native` | EXIF | The GPS of the video: GoPro (GPMF), CAMM, BlackVue, and Novatek-based dashcams | +| `native` | EXIF | The GPS of the video: GoPro (GPMF), CAMM, BlackVue, and Novatek-based dashcams; for a 70mai dashcam, its GPS log (`GPSData*.txt`) in the folder of the video | | `exif` | EXIF | Cannot read videos | | `exiftool_runtime` (`exiftool`) | Runs ExifTool on the image | Runs ExifTool on the video | | `exiftool_xml` | Reads the output of `exiftool -X`, by default `%g.xml` beside the file | The same | diff --git a/mapillary_tools/geotag/video_extractors/native.py b/mapillary_tools/geotag/video_extractors/native.py index 177168702..06dcb8db2 100644 --- a/mapillary_tools/geotag/video_extractors/native.py +++ b/mapillary_tools/geotag/video_extractors/native.py @@ -19,6 +19,7 @@ exceptions, geo, novatek_parser, + seventymai_log_parser, telemetry, types, utils, @@ -150,6 +151,28 @@ def extract(self) -> types.VideoMetadata: ) +class SeventymaiLogVideoExtractor(BaseVideoExtractor): + """ + Reads the GPS log that 70mai dashcams write beside their clips + """ + + @override + def extract(self) -> types.VideoMetadata: + points = seventymai_log_parser.extract_points(self.video_path) + + if not points: + raise exceptions.MapillaryVideoGPSNotFoundError( + "No GPS data found from the video" + ) + + return types.VideoMetadata( + filename=self.video_path, + filesize=utils.get_file_size(self.video_path), + filetype=types.FileType.VIDEO, + points=T.cast(T.List[geo.Point], points), + ) + + class NativeVideoExtractor(BaseVideoExtractor): def __init__( self, @@ -220,6 +243,14 @@ def extract(self) -> types.VideoMetadata: except exceptions.MapillaryVideoGPSNotFoundError: pass + # A video without GPS of its own may be a 70mai clip with a GPS log beside it + if ft is None or types.FileType.VIDEO in ft: + extractor = SeventymaiLogVideoExtractor(self.video_path) + try: + return extractor.extract() + except exceptions.MapillaryVideoGPSNotFoundError: + pass + raise exceptions.MapillaryVideoGPSNotFoundError( "No GPS data found from the video" ) diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py new file mode 100644 index 000000000..cbe5e65b6 --- /dev/null +++ b/mapillary_tools/seventymai_log_parser.py @@ -0,0 +1,302 @@ +# 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. + +""" +Read the GPS of a 70mai dashcam clip from the GPS log that the camera writes beside +its clips (GPSData000001.txt): the clips themselves have no GPS that can be read. + +The log is text: a line "$V02" each time the camera starts logging, then a row per +fix, for many clips and hours: + + 1717236900,A,47.376900,8.541700,9000,1250,-81,9,40,NO20240601-121500-000123F.MP4,0,0,0 + +The columns are the Unix time (UTC), the fix status (A: valid), the latitude and the +longitude in degrees, the course in centidegrees, the speed in cm/s, three unknown +values, the clip being recorded, and three unknown values. Rows that are not valid +fixes have no position, or a placeholder time (0, -28801, the start of 2021), or +null island. Some cameras write such rows, naming the clip, until they have a fix. +Others write none, or name no clip in them ("0"). + +The rows carry the GPS time of the fixes, not their time in the video. A camera +that has a fix when a clip starts, as in the middle of a recording, writes the first +row of the clip within about a second of its start, and the last within a few +seconds of its end: it writes a row every 1 to 1.5 seconds, and repeats a stale fix +while its GPS stalls, for up to 5 seconds. So the first fix of the clip is taken as +its start. A camera that is switched on records before it has a fix: its first fix +comes seconds, at times minutes, into the clip. Then it writes rows without a fix +before it, or the fixes span much less than the clip, and the last fix of the clip +is taken as its end instead. +""" + +from __future__ import annotations + +import functools +import logging +import math +import os +import typing as T +from pathlib import Path + +import construct as C + +from . import telemetry +from .mp4 import construct_mp4_parser as cparser, simple_mp4_parser as sparser + +LOG = logging.getLogger(__name__) + +# GPSData000001.txt, GPSData000002.txt, ... compared case-insensitively +_LOG_NAME_PREFIX = "gpsdata" +_LOG_NAME_SUFFIX = ".txt" + +_NUM_COLUMNS = 13 +_CLIP_COLUMN = 9 + +# The fixes of a clip that the camera recorded with a fix from its start span +# all of it but for a stall of its GPS at the start or the end, up to 6 seconds +# in the logs seen. Those of a clip whose first fix came late, as when the +# camera was switched on, span at least 9 seconds less +_MAX_MISSING_SECONDS = 8.0 + +# The fixes may span a few seconds more than the clip, as the camera may repeat +# the last fix of the previous clip as the first of the next. More than this, +# they are not of the clip as it is (e.g. a timelapse) +_MAX_EXCESS_SECONDS = 5.0 + + +class _Row(T.NamedTuple): + # (Unix time, latitude, longitude), or None if the row is not a valid fix + fix: tuple[int, float, float] | None + + +def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: + """ + Return the GPS points of the clip from the logs in its folder, sorted by time, + or None if there are no logs, no valid fixes of the clip in them, or they do + not fit the clip. Point time is the time in the video, and epoch_time is the + Unix time of the fix. + """ + folder = video_path.parent + try: + log_paths = _find_log_paths(folder, folder.stat().st_mtime_ns) + except OSError as ex: + LOG.debug("Unable to list %s for GPS logs: %s", folder, ex) + return None + + if not log_paths: + return None + + # The rows of the clip in the order the camera wrote them, which may be + # continued in the next log + rows: list[_Row] = [] + for log_path in log_paths: + try: + rows.extend(_read_clip_rows(log_path, video_path.stem.casefold())) + except OSError as ex: + LOG.warning("Unable to read the GPS log %s: %s", log_path, ex) + + fix_indices = [idx for idx, row in enumerate(rows) if row.fix is not None] + if not fix_indices: + LOG.debug("No fixes of %s in the GPS logs %s", video_path.name, log_paths) + return None + + duration = _read_duration(video_path) + if duration is None: + return None + + # The positions by time, without the stale fixes that the camera repeats + fixes: dict[int, tuple[float, float]] = {} + for idx in fix_indices: + fix = rows[idx].fix + assert fix is not None + fixes.setdefault(fix[0], (fix[1], fix[2])) + times = sorted(fixes) + + span = times[-1] - times[0] + if duration + _MAX_EXCESS_SECONDS < span: + LOG.warning( + "Ignoring the GPS log of %s: its fixes span %d seconds, more than the %.1f seconds of the video", + video_path.name, + span, + duration, + ) + return None + + no_fix_at_start = 0 < fix_indices[0] + no_fix_at_end = fix_indices[-1] < len(rows) - 1 + if no_fix_at_start and no_fix_at_end: + LOG.warning( + "Ignoring the GPS log of %s: the camera had no fix at the start nor at the end of the clip, so its fixes cannot be placed in the video", + video_path.name, + ) + return None + + if no_fix_at_start or ( + not no_fix_at_end and _MAX_MISSING_SECONDS < duration - span + ): + # The camera got its first fix after it started recording the clip + start_time = float(times[-1]) - duration + else: + start_time = float(times[0]) + + return [ + telemetry.GPSPoint( + time=t - start_time, + lat=fixes[t][0], + lon=fixes[t][1], + alt=None, + angle=None, + epoch_time=float(t), + fix=None, + precision=None, + ground_speed=None, + ) + for t in times + # Leave out the fixes that span more than the clip: the CAMM track of + # the upload starts at time 0 + if start_time <= t + ] + + +@functools.lru_cache(maxsize=64) +def _find_log_paths(folder: Path, mtime_ns: int) -> list[Path]: + """ + The GPS logs in the folder (GPSData000001.txt, ...), in the order of their + names. The modification time of the folder is part of the cache key + """ + with os.scandir(folder) as entries: + names = [ + entry.name + for entry in entries + if entry.name.casefold().startswith(_LOG_NAME_PREFIX) + and entry.name.casefold().endswith(_LOG_NAME_SUFFIX) + and entry.is_file() + ] + return [folder / name for name in sorted(names, key=str.casefold)] + + +def _read_clip_rows(log_path: Path, key: str) -> list[_Row]: + stat = log_path.stat() + index = _index_log(log_path, stat.st_size, stat.st_mtime_ns) + ranges = index.get(key) + if not ranges: + return [] + + rows: list[_Row] = [] + with log_path.open("rb") as fp: + for start, end in ranges: + fp.seek(start) + for line in fp.read(end - start).splitlines(): + row = _parse_row(line) + if row is not None: + rows.append(row) + return rows + + +@functools.lru_cache(maxsize=16) +def _index_log( + log_path: Path, size: int, mtime_ns: int +) -> dict[str, list[tuple[int, int]]]: + """ + Index the log by clip: the byte ranges of the runs of lines that name each clip. + A log may be tens of MB and is read by every clip it covers, so it is read once. + The size and the modification time of the log are part of the cache key + """ + index: dict[str, list[tuple[int, int]]] = {} + + def _add_run(name: bytes | None, start: int, end: int) -> None: + if name is None: + return + key = _clip_key(name) + if key is not None: + index.setdefault(key, []).append((start, end)) + + with log_path.open("rb") as fp: + offset = 0 + run_name: bytes | None = None + run_start = 0 + for line in fp: + fields = line.split(b",", _CLIP_COLUMN + 1) + name = fields[_CLIP_COLUMN] if _CLIP_COLUMN < len(fields) - 1 else None + if name != run_name: + _add_run(run_name, run_start, offset) + run_name = name + run_start = offset + offset += len(line) + _add_run(run_name, run_start, offset) + + return index + + +def _clip_key(name: bytes) -> str | None: + """ + The clip that a row names, as the stem of its file name, or None if the row + names none. Some cameras leave characters of a longer name after the extension + + >>> _clip_key(b"NO20240601-121500-000123F.MP44") + 'no20240601-121500-000123f' + >>> _clip_key(b"NO20240601-121500-000123F.mp4") + 'no20240601-121500-000123f' + >>> _clip_key(b"0") is None + True + """ + text = name.strip().decode("latin-1") + if "." not in text: + return None + stem = text.rsplit(".", 1)[0] + if not stem: + return None + return stem.casefold() + + +def _parse_row(line: bytes) -> _Row | None: + """ + Parse a row of the log, or return None if it is malformed + + >>> _parse_row(b"1717236900,A,47.376900,8.541700,9000,1250,-81,9,40,NO20240601-121500-000123F.MP4,0,0,0") + _Row(fix=(1717236900, 47.3769, 8.5417)) + >>> _parse_row(b"1609430400,V,0.000000,0.000000,0,0,0.00,0.00,0.00,NO20240601-121500-000123F.mp4,0,0,0") + _Row(fix=None) + >>> _parse_row(b"-28801,A,47.376900,8.541700,9000,1250,100,1,-18,NO20240601-121500-000123F.MP4,0,0,0") + _Row(fix=None) + >>> _parse_row(b"1717236900,A,47.376900,8.5417") is None + True + """ + fields = line.strip().split(b",") + if len(fields) != _NUM_COLUMNS: + return None + + try: + unix_time = int(fields[0]) + lat = float(fields[2]) + lon = float(fields[3]) + except ValueError: + return None + + if ( + fields[1].strip().upper() != b"A" + or unix_time <= 0 + or not (math.isfinite(lat) and math.isfinite(lon)) + or not (-90 <= lat <= 90 and -180 <= lon <= 180) + or (lat == 0 and lon == 0) + ): + return _Row(fix=None) + + return _Row(fix=(unix_time, lat, lon)) + + +def _read_duration(video_path: Path) -> float | None: + try: + with video_path.open("rb") as fp: + data = sparser.parse_mp4_data_first(fp, [b"moov", b"mvhd"]) + if data is None: + return None + mvhd = cparser.MovieHeaderBox.parse(data) + except (OSError, sparser.ParsingError, C.ConstructError) as ex: + LOG.debug("Unable to read the duration of %s: %s", video_path, ex) + return None + + if not mvhd.timescale or mvhd.duration <= 0: + return None + return mvhd.duration / mvhd.timescale diff --git a/tests/unit/test_seventymai_log_parser.py b/tests/unit/test_seventymai_log_parser.py new file mode 100644 index 000000000..bb80a8628 --- /dev/null +++ b/tests/unit/test_seventymai_log_parser.py @@ -0,0 +1,288 @@ +# 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. + +from __future__ import annotations + +import datetime +import struct +from pathlib import Path + +import pytest + +from mapillary_tools import ( + exceptions, + process_geotag_properties as pgp, + sample_video, + seventymai_log_parser, + types, +) +from mapillary_tools.geotag.video_extractors.gpx import GPXVideoExtractor +from mapillary_tools.geotag.video_extractors.native import NativeVideoExtractor + +CLIP = "NO20240601-121500-000123F.MP4" +PREVIOUS_CLIP = "NO20240601-121400-000122F.MP4" +NEXT_CLIP = "NO20240601-121600-000124F.MP4" + +# The start of the clip by the GPS clock +START = 1717236900 + + +def _box(box_type: bytes, data: bytes) -> bytes: + return struct.pack(">I", 8 + len(data)) + box_type + data + + +def _build_video(duration: float) -> bytes: + """A video with no GPS of its own, as 70mai clips are, of the given duration""" + ftyp = _box(b"ftyp", b"mp42\x00\x00\x00\x00isomavc1mp42") + mvhd = struct.pack(">4xIIII", 0, 0, 1000, int(duration * 1000)).ljust(100, b"\x00") + return ftyp + _box(b"moov", _box(b"mvhd", mvhd)) + + +def _position(t: int) -> tuple[float, float]: + # As the log writes them, to 6 decimals + return ( + round(47.3769 + (t - START) * 0.0001, 6), + round(8.5417 + (t - START) * 0.0002, 6), + ) + + +def _row(t: int, clip: str = CLIP, status: str = "A") -> str: + lat, lon = _position(t) + return f"{t},{status},{lat:.6f},{lon:.6f},11500,2388,-81,9,40,{clip},0,0,0" + + +def _rows(times, clip: str = CLIP) -> list[str]: + return [_row(t, clip) for t in times] + + +def _no_fix_row(clip: str = CLIP) -> str: + # A camera without a fix writes a placeholder time and no position + return f"1609430400,V,0.000000,0.000000,0,0,0.00,0.00,0.00,{clip},0,0,0" + + +def _write(folder: Path, lines: list[str], name: str = "GPSData000001.txt") -> None: + folder.joinpath(name).write_text("\n".join(["$V02", *lines]) + "\n") + + +def _clip(folder: Path, name: str = CLIP, duration: float = 60.0) -> Path: + video_path = folder / name + video_path.write_bytes(_build_video(duration)) + return video_path + + +def _extract(video_path: Path) -> list[tuple[float, float, float, float | None]]: + points = NativeVideoExtractor(video_path).extract().points + return [(p.time, p.lat, p.lon, p.epoch_time) for p in points] # type: ignore + + +def _expected(times, start_time: float) -> list[tuple[float, float, float, float]]: + return [(t - start_time, *_position(t), float(t)) for t in times] + + +# The rows of a clip recorded in the middle of a recording: a row every 1.5 +# seconds, sometimes a stale fix repeated (START + 4) +CLIP_TIMES = [START + t for t in (0, 1, 3, 4, 6, 7, 9, 10, 12, 13)] + [ + START + t for t in range(15, 60, 2) +] + + +def test_clip_recorded_with_a_fix(tmp_path: Path): + video_path = _clip(tmp_path) + _write( + tmp_path, + [ + *_rows(range(START - 60, START, 2), PREVIOUS_CLIP), + *_rows(CLIP_TIMES[:4]), + _row(START + 4), + # Not valid fixes, nor rows of the log + _no_fix_row(), + _row(START + 5, status="V"), + f"{START + 5},A,0.000000,0.000000,0,0,0,0,0,{CLIP},0,0,0", + f"{START + 5},A, 0.000000, nan,0,0,0,0,0,{CLIP},0,0,0", + f"-28801,A,47.377400,8.542700,0,0,0,0,0,{CLIP},0,0,0", + f"{START + 5},A,47.377400,8.542700,0,0,0,{CLIP},0,0,0", + f"x,A,47.377400,8.542700,0,0,0,0,0,{CLIP},0,0,0", + *_rows(CLIP_TIMES[4:]), + "0,V, 0.000000, nan,-1,45,0,0,0,0,0,0,0", + *_rows(range(START + 60, START + 120, 2), NEXT_CLIP), + ], + ) + + # The first fix marks the start of the clip + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + metadata = NativeVideoExtractor(video_path).extract() + assert metadata.filetype == types.FileType.VIDEO + assert metadata.make is None and metadata.model is None + + +def test_first_fix_came_late(tmp_path: Path): + # A camera that is switched on records before it has a fix, and some + # write no rows until then + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if START + 20 <= t] + _write(tmp_path, _rows(times)) + + # The last fix marks the end of the clip + assert _extract(video_path) == _expected(times, times[-1] - 60.0) + + +def test_first_fix_came_a_few_seconds_late(tmp_path: Path): + # As late as a stall of the GPS in the middle of a recording + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if START + 6 <= t] + _write(tmp_path, _rows(times)) + + assert _extract(video_path) == _expected(times, times[0]) + + +def test_rows_without_a_fix_before_the_first_fix(tmp_path: Path): + # Others write rows without a fix until then + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if START + 3 <= t] + _write(tmp_path, [_no_fix_row(), _no_fix_row(), *_rows(times)]) + + assert _extract(video_path) == _expected(times, times[-1] - 60.0) + + +def test_rows_without_a_fix_after_the_last_fix(tmp_path: Path): + # The camera lost its fix before the end of the clip + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if t < START + 30] + _write(tmp_path, [*_rows(times), _no_fix_row(), _no_fix_row()]) + + assert _extract(video_path) == _expected(times, times[0]) + + +def test_rows_without_a_fix_at_both_ends(tmp_path: Path): + video_path = _clip(tmp_path) + _write(tmp_path, [_no_fix_row(), *_rows(CLIP_TIMES[5:-5]), _no_fix_row()]) + + with pytest.raises(exceptions.MapillaryVideoGPSNotFoundError): + NativeVideoExtractor(video_path).extract() + + +def test_fixes_span_a_few_seconds_more_than_the_clip(tmp_path: Path): + video_path = _clip(tmp_path, duration=57.5) + _write(tmp_path, _rows(CLIP_TIMES)) + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + # Placed by the last fix, those that span more than the clip are left out + _write(tmp_path, [_no_fix_row(), *_rows(CLIP_TIMES)]) + assert _extract(video_path) == _expected(CLIP_TIMES[2:], CLIP_TIMES[-1] - 57.5) + + +def test_fixes_span_much_more_than_the_clip(tmp_path: Path): + video_path = _clip(tmp_path, duration=2.0) + _write(tmp_path, _rows(CLIP_TIMES)) + + with pytest.raises(exceptions.MapillaryVideoGPSNotFoundError): + NativeVideoExtractor(video_path).extract() + + +def test_no_rows_of_the_clip(tmp_path: Path): + video_path = _clip(tmp_path) + with pytest.raises(exceptions.MapillaryVideoGPSNotFoundError): + NativeVideoExtractor(video_path).extract() + + _write(tmp_path, [*_rows(CLIP_TIMES, PREVIOUS_CLIP), _no_fix_row()]) + with pytest.raises(exceptions.MapillaryVideoGPSNotFoundError): + NativeVideoExtractor(video_path).extract() + + +@pytest.mark.parametrize( + "logged_name", + [ + "NO20240601-121500-000123F.MP4", + # A camera that leaves characters of a longer name behind + "NO20240601-121500-000123F.MP44", + "NO20240601-121500-000123F.mp4", + "no20240601-121500-000123f.MP4", + ], +) +def test_clip_names(tmp_path: Path, logged_name: str): + video_path = _clip(tmp_path, name="NO20240601-121500-000123F.mp4") + _write(tmp_path, _rows(CLIP_TIMES, logged_name)) + + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + +def test_rows_continued_in_the_next_log(tmp_path: Path): + video_path = _clip(tmp_path) + _write(tmp_path, _rows(CLIP_TIMES[:10]), name="GPSData000001.txt") + _write(tmp_path, _rows(CLIP_TIMES[10:]), name="gpsdata000002.TXT") + # Not a log + _write(tmp_path, _rows([START - 30]), name="notes.txt") + + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + +def test_log_read_once_for_all_its_clips(tmp_path: Path): + _write( + tmp_path, + [*_rows(CLIP_TIMES), *_rows(range(START + 60, START + 120, 2), NEXT_CLIP)], + ) + seventymai_log_parser._index_log.cache_clear() + + assert _extract(_clip(tmp_path)) == _expected(CLIP_TIMES, START) + assert _extract(_clip(tmp_path, name=NEXT_CLIP)) == _expected( + range(START + 60, START + 120, 2), START + 60 + ) + assert seventymai_log_parser._index_log.cache_info().misses == 1 + + +def test_file_types(tmp_path: Path): + video_path = _clip(tmp_path) + _write(tmp_path, _rows(CLIP_TIMES)) + + assert NativeVideoExtractor(video_path, filetypes={types.FileType.VIDEO}).extract() + # Not one of the native file types + with pytest.raises(exceptions.MapillaryVideoGPSNotFoundError): + NativeVideoExtractor(video_path, filetypes={types.FileType.CAMM}).extract() + + +def test_process(tmp_path: Path): + video_path = _clip(tmp_path) + _write(tmp_path, _rows(CLIP_TIMES)) + + [metadata] = pgp.process_geotag_properties( + tmp_path, + None, + geotag_source=[], + geotag_source_path=None, + video_geotag_source=[], + ) + + assert isinstance(metadata, types.VideoMetadata), metadata + assert metadata.filename == video_path + assert [(p.time, p.lat, p.lon) for p in metadata.points] == [ + (t - START, *_position(t)) for t in CLIP_TIMES + ] + + +def test_sample_video_reads_the_clock(tmp_path: Path): + video_path = _clip(tmp_path) + _write(tmp_path, _rows(CLIP_TIMES)) + + points = sample_video._read_telemetry(video_path) + assert sample_video._gps_clock_start_time( + points + ) == datetime.datetime.fromtimestamp(START, tz=datetime.timezone.utc) + + +def test_gpx_sync(tmp_path: Path): + video_path = _clip(tmp_path) + _write(tmp_path, _rows(CLIP_TIMES)) + gpx_path = tmp_path / "track.gpx" + gpx_path.write_text( + '' + '' + '' + '' + "" + ) + # The GPX track is placed by the GPS clock of the log + video_metadata = GPXVideoExtractor(video_path, gpx_path).extract() + assert [p.time for p in video_metadata.points] == [-10.0, 0.0, 10.0] From 326ff19cd4dbdda4abc8cec4e6337f968ac65b67 Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Fri, 27 Nov 2026 10:26:03 +0100 Subject: [PATCH 2/8] Place a short 70mai clip by its last fix only if it starts the log A clip without rows without a fix was placed by its last fix, as the end of the clip, whenever its fixes spanned more than 8 seconds less than the clip. That is meant for the first clip after the camera is switched on, whose first fix comes late. But in the middle of a logging session, the clips that the rule placed are all the last clip before the camera restarted logging ("$V02"): the camera had a fix when it started the clip, and stopped recording or logging it early. Their first fix marks their start, and placing them by their last fix shifted them by 13 to 119 seconds in one of the logs seen. The index of a log now records where each run of rows of a clip is: after "$V02" (or rows that name no clip), at the top of the log, or after rows of another clip. The span rule applies only to a clip whose first rows follow "$V02", or are at the top of the first log in the folder, as the top of a later log continues the previous one. Rows without a fix before the first fix still place a clip by its last fix wherever it is. In three logs, 58 clips are placed by their first fix instead of their last. For all of them, the last fix of the previous clip is 0 to 5 seconds before their first fix. For 52, the start this gives is also within 3 seconds of the start that the previous clip gives from the time in the file names. --- mapillary_tools/seventymai_log_parser.py | 88 +++++++++++++++--------- tests/unit/test_seventymai_log_parser.py | 81 ++++++++++++++++++++-- 2 files changed, 134 insertions(+), 35 deletions(-) diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py index cbe5e65b6..5fd941355 100644 --- a/mapillary_tools/seventymai_log_parser.py +++ b/mapillary_tools/seventymai_log_parser.py @@ -25,9 +25,12 @@ seconds of its end: it writes a row every 1 to 1.5 seconds, and repeats a stale fix while its GPS stalls, for up to 5 seconds. So the first fix of the clip is taken as its start. A camera that is switched on records before it has a fix: its first fix -comes seconds, at times minutes, into the clip. Then it writes rows without a fix -before it, or the fixes span much less than the clip, and the last fix of the clip -is taken as its end instead. +comes seconds, at times minutes, into the clip. Then the last fix of the clip is +taken as its end instead, if the camera wrote rows without a fix that name the clip +before its first fix, or if the clip is the first that the camera logged after it +started logging ("$V02") and its fixes span much less than the clip. Any other clip +whose fixes span much less ended early, as the camera stopped recording it: the +next line of the log is "$V02". """ from __future__ import annotations @@ -53,12 +56,19 @@ _NUM_COLUMNS = 13 _CLIP_COLUMN = 9 -# The fixes of a clip that the camera recorded with a fix from its start span -# all of it but for a stall of its GPS at the start or the end, up to 6 seconds -# in the logs seen. Those of a clip whose first fix came late, as when the -# camera was switched on, span at least 9 seconds less +# The fixes of the first clip that the camera logged after it started logging +# span all of it but for a stall of its GPS, up to 6 seconds in the logs seen, +# if it had a fix from the start of the clip. If its first fix came late, as +# when the camera was switched on, they span at least 9 seconds less _MAX_MISSING_SECONDS = 8.0 +# Where the first run of the rows of a clip is in a log: right after "$V02" (or +# after rows that name no clip), at the top of the log, or after rows of another +# clip +_AFTER_HEADER = "header" +_AT_TOP = "top" +_AFTER_CLIP = "clip" + # The fixes may span a few seconds more than the clip, as the camera may repeat # the last fix of the previous clip as the first of the next. More than this, # they are not of the clip as it is (e.g. a timelapse) @@ -88,13 +98,22 @@ def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: return None # The rows of the clip in the order the camera wrote them, which may be - # continued in the next log + # continued in the next log, and whether they are the first rows that the + # camera wrote after it started logging rows: list[_Row] = [] - for log_path in log_paths: + first_logged: bool | None = None + for log_idx, log_path in enumerate(log_paths): try: - rows.extend(_read_clip_rows(log_path, video_path.stem.casefold())) + clip_rows, begins = _read_clip_rows(log_path, video_path.stem.casefold()) except OSError as ex: LOG.warning("Unable to read the GPS log %s: %s", log_path, ex) + continue + if first_logged is None and begins is not None: + # The top of a later log continues the previous log + first_logged = begins == _AFTER_HEADER or ( + begins == _AT_TOP and log_idx == 0 + ) + rows.extend(clip_rows) fix_indices = [idx for idx, row in enumerate(rows) if row.fix is not None] if not fix_indices: @@ -133,7 +152,7 @@ def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: return None if no_fix_at_start or ( - not no_fix_at_end and _MAX_MISSING_SECONDS < duration - span + first_logged and not no_fix_at_end and _MAX_MISSING_SECONDS < duration - span ): # The camera got its first fix after it started recording the clip start_time = float(times[-1]) - duration @@ -176,55 +195,62 @@ def _find_log_paths(folder: Path, mtime_ns: int) -> list[Path]: return [folder / name for name in sorted(names, key=str.casefold)] -def _read_clip_rows(log_path: Path, key: str) -> list[_Row]: +def _read_clip_rows(log_path: Path, key: str) -> tuple[list[_Row], str | None]: + """ + The rows of the clip in the log, and where their first run is in it (see + _AFTER_HEADER), or None if the log has no rows of the clip + """ stat = log_path.stat() index = _index_log(log_path, stat.st_size, stat.st_mtime_ns) - ranges = index.get(key) - if not ranges: - return [] + runs = index.get(key) + if not runs: + return [], None rows: list[_Row] = [] with log_path.open("rb") as fp: - for start, end in ranges: + for start, end, _ in runs: fp.seek(start) for line in fp.read(end - start).splitlines(): row = _parse_row(line) if row is not None: rows.append(row) - return rows + return rows, runs[0][2] @functools.lru_cache(maxsize=16) def _index_log( log_path: Path, size: int, mtime_ns: int -) -> dict[str, list[tuple[int, int]]]: +) -> dict[str, list[tuple[int, int, str]]]: """ - Index the log by clip: the byte ranges of the runs of lines that name each clip. - A log may be tens of MB and is read by every clip it covers, so it is read once. - The size and the modification time of the log are part of the cache key + Index the log by clip: the byte ranges of the runs of lines that name each + clip, and where each run is (see _AFTER_HEADER). A log may be tens of MB and + is read by every clip it covers, so it is read once. The size and the + modification time of the log are part of the cache key """ - index: dict[str, list[tuple[int, int]]] = {} - - def _add_run(name: bytes | None, start: int, end: int) -> None: - if name is None: - return - key = _clip_key(name) - if key is not None: - index.setdefault(key, []).append((start, end)) + index: dict[str, list[tuple[int, int, str]]] = {} with log_path.open("rb") as fp: offset = 0 run_name: bytes | None = None run_start = 0 + run_where = position = _AT_TOP for line in fp: fields = line.split(b",", _CLIP_COLUMN + 1) name = fields[_CLIP_COLUMN] if _CLIP_COLUMN < len(fields) - 1 else None if name != run_name: - _add_run(run_name, run_start, offset) + key = None if run_name is None else _clip_key(run_name) + if key is not None: + index.setdefault(key, []).append((run_start, offset, run_where)) + position = _AFTER_CLIP run_name = name run_start = offset + run_where = position + if line.startswith(b"$"): + position = _AFTER_HEADER offset += len(line) - _add_run(run_name, run_start, offset) + key = None if run_name is None else _clip_key(run_name) + if key is not None: + index.setdefault(key, []).append((run_start, offset, run_where)) return index diff --git a/tests/unit/test_seventymai_log_parser.py b/tests/unit/test_seventymai_log_parser.py index bb80a8628..4b1699dff 100644 --- a/tests/unit/test_seventymai_log_parser.py +++ b/tests/unit/test_seventymai_log_parser.py @@ -62,8 +62,16 @@ def _no_fix_row(clip: str = CLIP) -> str: return f"1609430400,V,0.000000,0.000000,0,0,0.00,0.00,0.00,{clip},0,0,0" -def _write(folder: Path, lines: list[str], name: str = "GPSData000001.txt") -> None: - folder.joinpath(name).write_text("\n".join(["$V02", *lines]) + "\n") +def _write( + folder: Path, + lines: list[str], + name: str = "GPSData000001.txt", + header: bool = True, +) -> None: + # The camera writes "$V02" each time it starts logging + folder.joinpath(name).write_text( + "\n".join(["$V02", *lines] if header else lines) + "\n" + ) def _clip(folder: Path, name: str = CLIP, duration: float = 60.0) -> Path: @@ -118,17 +126,82 @@ def test_clip_recorded_with_a_fix(tmp_path: Path): assert metadata.make is None and metadata.model is None -def test_first_fix_came_late(tmp_path: Path): +@pytest.mark.parametrize( + "before", + [ + [], + # Rows that name no clip, nor are rows of the log + ["0,V, 0.000000, nan,-1,45,0,0,0,0,0,0,0", "1717236800,A,47.3"], + # The camera logged another recording before + [*_rows(range(START - 3600, START - 3540, 2), PREVIOUS_CLIP), "$V02"], + ], +) +def test_first_fix_came_late(tmp_path: Path, before: list[str]): # A camera that is switched on records before it has a fix, and some # write no rows until then video_path = _clip(tmp_path) times = [t for t in CLIP_TIMES if START + 20 <= t] - _write(tmp_path, _rows(times)) + _write(tmp_path, [*before, *_rows(times)]) # The last fix marks the end of the clip assert _extract(video_path) == _expected(times, times[-1] - 60.0) +def test_first_fix_came_late_at_the_top_of_the_first_log(tmp_path: Path): + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if START + 20 <= t] + _write(tmp_path, _rows(times), header=False) + + assert _extract(video_path) == _expected(times, times[-1] - 60.0) + + +def test_clip_ended_early(tmp_path: Path): + # The camera stopped recording, and logging, 20 seconds into the clip. + # Its fixes span much less than the clip, but the camera had a fix when it + # started the clip: it logged the previous one + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if t <= START + 20] + _write( + tmp_path, + [ + *_rows(range(START - 60, START, 2), PREVIOUS_CLIP), + *_rows(times), + "$V02", + *_rows(range(START + 100, START + 160, 2), NEXT_CLIP), + ], + ) + + # The first fix marks the start of the clip + assert _extract(video_path) == _expected(times, times[0]) + + +def test_clip_logged_across_a_restart_of_the_log(tmp_path: Path): + # Where its rows start tells whether the camera had a fix at its start + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if t <= START + 10 or START + 30 <= t <= START + 40] + _write( + tmp_path, + [ + *_rows(range(START - 60, START, 2), PREVIOUS_CLIP), + *_rows(t for t in times if t <= START + 10), + "$V02", + *_rows(t for t in times if START + 30 <= t), + ], + ) + + assert _extract(video_path) == _expected(times, times[0]) + + +def test_short_clip_at_the_top_of_the_next_log(tmp_path: Path): + # The next log continues the previous one, without "$V02" + video_path = _clip(tmp_path) + times = [t for t in CLIP_TIMES if t <= START + 20] + _write(tmp_path, _rows(range(START - 60, START, 2), PREVIOUS_CLIP)) + _write(tmp_path, _rows(times), name="GPSData000002.txt", header=False) + + assert _extract(video_path) == _expected(times, times[0]) + + def test_first_fix_came_a_few_seconds_late(tmp_path: Path): # As late as a stall of the GPS in the middle of a recording video_path = _clip(tmp_path) From d4a246bd7d5c81b0303e8088efeaad16bd7395e6 Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Fri, 27 Nov 2026 11:11:28 +0100 Subject: [PATCH 3/8] Take only "$V02" as where the camera started logging The top of the first log in a folder was taken as where the camera started logging, like a "$V02" line, so a short clip there was placed by its last fix. A log without "$V02" at its top more likely continues one that was cut or rotated away, and for a clip continued from a log, the first fix is the right start. Only rows right after "$V02" now count as the first the camera logged. --- mapillary_tools/seventymai_log_parser.py | 15 ++++++--------- tests/unit/test_seventymai_log_parser.py | 6 ++++-- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py index 5fd941355..7b83a947a 100644 --- a/mapillary_tools/seventymai_log_parser.py +++ b/mapillary_tools/seventymai_log_parser.py @@ -63,10 +63,10 @@ _MAX_MISSING_SECONDS = 8.0 # Where the first run of the rows of a clip is in a log: right after "$V02" (or -# after rows that name no clip), at the top of the log, or after rows of another -# clip +# after rows that name no clip), where the camera started logging, or elsewhere: +# after rows of another clip, or at the top of a log without "$V02", which +# continues a log _AFTER_HEADER = "header" -_AT_TOP = "top" _AFTER_CLIP = "clip" # The fixes may span a few seconds more than the clip, as the camera may repeat @@ -102,17 +102,14 @@ def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: # camera wrote after it started logging rows: list[_Row] = [] first_logged: bool | None = None - for log_idx, log_path in enumerate(log_paths): + for log_path in log_paths: try: clip_rows, begins = _read_clip_rows(log_path, video_path.stem.casefold()) except OSError as ex: LOG.warning("Unable to read the GPS log %s: %s", log_path, ex) continue if first_logged is None and begins is not None: - # The top of a later log continues the previous log - first_logged = begins == _AFTER_HEADER or ( - begins == _AT_TOP and log_idx == 0 - ) + first_logged = begins == _AFTER_HEADER rows.extend(clip_rows) fix_indices = [idx for idx, row in enumerate(rows) if row.fix is not None] @@ -233,7 +230,7 @@ def _index_log( offset = 0 run_name: bytes | None = None run_start = 0 - run_where = position = _AT_TOP + run_where = position = _AFTER_CLIP for line in fp: fields = line.split(b",", _CLIP_COLUMN + 1) name = fields[_CLIP_COLUMN] if _CLIP_COLUMN < len(fields) - 1 else None diff --git a/tests/unit/test_seventymai_log_parser.py b/tests/unit/test_seventymai_log_parser.py index 4b1699dff..1152eb7b3 100644 --- a/tests/unit/test_seventymai_log_parser.py +++ b/tests/unit/test_seventymai_log_parser.py @@ -147,12 +147,14 @@ def test_first_fix_came_late(tmp_path: Path, before: list[str]): assert _extract(video_path) == _expected(times, times[-1] - 60.0) -def test_first_fix_came_late_at_the_top_of_the_first_log(tmp_path: Path): +def test_short_clip_at_the_top_of_a_log_without_header(tmp_path: Path): + # A log without "$V02" continues one that is not there, such as one cut or + # rotated away, so its first rows don't tell when the camera got a fix video_path = _clip(tmp_path) times = [t for t in CLIP_TIMES if START + 20 <= t] _write(tmp_path, _rows(times), header=False) - assert _extract(video_path) == _expected(times, times[-1] - 60.0) + assert _extract(video_path) == _expected(times, times[0]) def test_clip_ended_early(tmp_path: Path): From 3d73ede9ccd45750fb32a4395a74ec435220f5b7 Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Tue, 1 Dec 2026 15:13:38 +0100 Subject: [PATCH 4/8] Tell from the clip names whether a 70mai GPS log is 8 hours behind UTC The GPS logs of 70mai dashcams were read as UTC, but on some cameras their times are 8 hours behind UTC: the firmware takes the UTC time of the GPS for the local time of China (UTC+8). On two of three sample cameras, every clip was stamped 8 hours early. The light in the clips shows it: a clip that the camera's clock, printed on the frames, has at 07:37 is in morning light, while the log read as UTC puts it at 23:36 local time. On the third camera, the log is UTC. The file name of a clip is the time of the camera's clock at its start, in local time. Once the log's time is UTC, the difference between the name and the clip's first fix is the time zone where the clip was recorded. Time zones are within about 3 hours of the solar time of their longitude (the most, in west China), and the two clocks are 8 hours apart, so at most one gives a zone within 4 hours. Each clip now takes the shift, none or 8 hours, that its name tells. A clip whose name tells neither, as when the camera's clock was not set, takes the shift that most of the clips in the logs of its folder tell. If they tell none, or are split evenly, the log is not used and a warning says why: the clip gets no GPS, as before the log was read. A difference outside UTC-12 to UTC+14 is no zone: a clock left in the time of China in America is 16 hours ahead of a log 8 hours behind, which would otherwise wrap around to a zone of America. In the three sample logs, every clip with a fix tells the same shift: 8 hours for all 60 and 115 clips of two logs recorded in UTC+2 and UTC+5, and none for 4,394 clips of a log recorded in UTC+3. The light in the clips matches their times now. Indexing a 60 MB log takes 0.3 s instead of 0.2 s, as it parses the rows of each clip up to its first fix. A GPX that GPSBabel converted from a log 8 hours behind has the same times, so it no longer lines up with the clip's clock, now UTC: process refuses it as outside the GPX track. These clips don't need it, as they get their GPS from the log. --- mapillary_tools/seventymai_log_parser.py | 186 +++++++++++++++++++---- tests/unit/test_seventymai_log_parser.py | 127 +++++++++++++++- 2 files changed, 281 insertions(+), 32 deletions(-) diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py index 7b83a947a..e35187216 100644 --- a/mapillary_tools/seventymai_log_parser.py +++ b/mapillary_tools/seventymai_log_parser.py @@ -12,12 +12,22 @@ 1717236900,A,47.376900,8.541700,9000,1250,-81,9,40,NO20240601-121500-000123F.MP4,0,0,0 -The columns are the Unix time (UTC), the fix status (A: valid), the latitude and the -longitude in degrees, the course in centidegrees, the speed in cm/s, three unknown -values, the clip being recorded, and three unknown values. Rows that are not valid -fixes have no position, or a placeholder time (0, -28801, the start of 2021), or -null island. Some cameras write such rows, naming the clip, until they have a fix. -Others write none, or name no clip in them ("0"). +The columns are the Unix time of the fix, the fix status (A: valid), the latitude and +the longitude in degrees, the course in centidegrees, the speed in cm/s, three +unknown values, the clip being recorded, and three unknown values. Rows that are not +valid fixes have no position, or a placeholder time (0, -28801, the start of 2021), +or null island. Some cameras write such rows, naming the clip, until they have a +fix. Others write none, or name no clip in them ("0"). + +The Unix time is UTC on some cameras, and 8 hours behind UTC on others, whose +firmware takes the UTC time of the GPS for the local time of China (UTC+8). The +file name of a clip tells which: it is the time of the camera's clock at the start +of the clip, in local time, so the difference from the time of its first fix is +the time zone where it was recorded, once the log's time is UTC. Time zones are +within about 3 hours of the solar time of their longitude, and the two clocks are +8 hours apart, so at most one gives a zone that fits. A clip whose name fits +neither, as when the camera's clock was not set, takes the clock that most of the +other clips in the logs fit. If none fits, the log is not used. The rows carry the GPS time of the fixes, not their time in the video. A camera that has a fix when a clip starts, as in the middle of a recording, writes the first @@ -35,10 +45,13 @@ from __future__ import annotations +import collections +import datetime import functools import logging import math import os +import re import typing as T from pathlib import Path @@ -74,18 +87,43 @@ # they are not of the clip as it is (e.g. a timelapse) _MAX_EXCESS_SECONDS = 5.0 +# The seconds to add to the times of a log to make them UTC: none, or 8 hours +# if the camera takes the UTC time of its GPS for the local time of China +_CLOCK_SHIFTS = (0, 8 * 3600) + +# Time zones are within about 3 hours of the solar time of their longitude (most +# in west China: UTC+8 at 74°E, where the sun says UTC+5), and from UTC-12 to +# UTC+14 +_MAX_ZONE_FROM_SOLAR_HOURS = 4.0 +_MIN_ZONE_HOURS = -12.0 +_MAX_ZONE_HOURS = 14.0 + +# The time of the camera's clock at the start of a clip, in its file name +# (NO20240601-121500-000123F.MP4) +_CLIP_CLOCK_PATTERN = re.compile(r"[a-z]*(\d{8}-\d{6})(?!\d)") + class _Row(T.NamedTuple): # (Unix time, latitude, longitude), or None if the row is not a valid fix fix: tuple[int, float, float] | None +class _LogIndex(T.NamedTuple): + # The byte ranges of the runs of lines that name each clip, and where each + # run is (see _AFTER_HEADER) + runs: dict[str, list[tuple[int, int, str]]] + # The seconds to add to the times of each clip to make them UTC, as its + # file name tells (see _clock_shift_of_clip), for the clips whose name tells + clock_shifts: dict[str, int] + + def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: """ Return the GPS points of the clip from the logs in its folder, sorted by time, or None if there are no logs, no valid fixes of the clip in them, or they do - not fit the clip. Point time is the time in the video, and epoch_time is the - Unix time of the fix. + not fit the clip, or the clip names in them do not tell whether their times are + UTC. Point time is the time in the video, and epoch_time is the Unix time of + the fix, in UTC. """ folder = video_path.parent try: @@ -100,14 +138,18 @@ def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: # The rows of the clip in the order the camera wrote them, which may be # continued in the next log, and whether they are the first rows that the # camera wrote after it started logging + key = video_path.stem.casefold() rows: list[_Row] = [] first_logged: bool | None = None + indices: list[_LogIndex] = [] for log_path in log_paths: try: - clip_rows, begins = _read_clip_rows(log_path, video_path.stem.casefold()) + index = _load_index(log_path) + clip_rows, begins = _read_clip_rows(log_path, index, key) except OSError as ex: LOG.warning("Unable to read the GPS log %s: %s", log_path, ex) continue + indices.append(index) if first_logged is None and begins is not None: first_logged = begins == _AFTER_HEADER rows.extend(clip_rows) @@ -148,6 +190,20 @@ def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: ) return None + clock_shift = _clock_shift(key, indices) + if clock_shift is None: + LOG.warning( + "Ignoring the GPS log of %s: some 70mai cameras log the GPS time 8 hours behind UTC, and the clip names in the log, which have the time of the camera's clock, do not tell whether this one does", + video_path.name, + ) + return None + if clock_shift: + LOG.debug( + "Adding %d hours to the times of %s in the GPS log", + clock_shift // 3600, + video_path.name, + ) + if no_fix_at_start or ( first_logged and not no_fix_at_end and _MAX_MISSING_SECONDS < duration - span ): @@ -163,7 +219,7 @@ def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: lon=fixes[t][1], alt=None, angle=None, - epoch_time=float(t), + epoch_time=float(t + clock_shift), fix=None, precision=None, ground_speed=None, @@ -192,14 +248,19 @@ def _find_log_paths(folder: Path, mtime_ns: int) -> list[Path]: return [folder / name for name in sorted(names, key=str.casefold)] -def _read_clip_rows(log_path: Path, key: str) -> tuple[list[_Row], str | None]: +def _load_index(log_path: Path) -> _LogIndex: + stat = log_path.stat() + return _index_log(log_path, stat.st_size, stat.st_mtime_ns) + + +def _read_clip_rows( + log_path: Path, index: _LogIndex, key: str +) -> tuple[list[_Row], str | None]: """ The rows of the clip in the log, and where their first run is in it (see _AFTER_HEADER), or None if the log has no rows of the clip """ - stat = log_path.stat() - index = _index_log(log_path, stat.st_size, stat.st_mtime_ns) - runs = index.get(key) + runs = index.runs.get(key) if not runs: return [], None @@ -215,41 +276,110 @@ def _read_clip_rows(log_path: Path, key: str) -> tuple[list[_Row], str | None]: @functools.lru_cache(maxsize=16) -def _index_log( - log_path: Path, size: int, mtime_ns: int -) -> dict[str, list[tuple[int, int, str]]]: +def _index_log(log_path: Path, size: int, mtime_ns: int) -> _LogIndex: """ Index the log by clip: the byte ranges of the runs of lines that name each - clip, and where each run is (see _AFTER_HEADER). A log may be tens of MB and - is read by every clip it covers, so it is read once. The size and the - modification time of the log are part of the cache key + clip, where each run is (see _AFTER_HEADER), and the clock that the name of + each clip tells. A log may be tens of MB and is read by every clip it covers, + so it is read once. The size and the modification time of the log are part + of the cache key """ - index: dict[str, list[tuple[int, int, str]]] = {} + runs: dict[str, list[tuple[int, int, str]]] = {} + # The time and the longitude of the first fix of each clip + first_fixes: dict[str, tuple[int, float]] = {} with log_path.open("rb") as fp: offset = 0 run_name: bytes | None = None + run_key: str | None = None run_start = 0 run_where = position = _AFTER_CLIP for line in fp: fields = line.split(b",", _CLIP_COLUMN + 1) name = fields[_CLIP_COLUMN] if _CLIP_COLUMN < len(fields) - 1 else None if name != run_name: - key = None if run_name is None else _clip_key(run_name) - if key is not None: - index.setdefault(key, []).append((run_start, offset, run_where)) + if run_key is not None: + runs.setdefault(run_key, []).append((run_start, offset, run_where)) position = _AFTER_CLIP run_name = name + run_key = None if name is None else _clip_key(name) run_start = offset run_where = position + if run_key is not None and run_key not in first_fixes: + row = _parse_row(line) + if row is not None and row.fix is not None: + first_fixes[run_key] = (row.fix[0], row.fix[2]) if line.startswith(b"$"): position = _AFTER_HEADER offset += len(line) - key = None if run_name is None else _clip_key(run_name) - if key is not None: - index.setdefault(key, []).append((run_start, offset, run_where)) + if run_key is not None: + runs.setdefault(run_key, []).append((run_start, offset, run_where)) - return index + clock_shifts: dict[str, int] = {} + for key, (unix_time, lon) in first_fixes.items(): + shift = _clock_shift_of_clip(key, unix_time, lon) + if shift is not None: + clock_shifts[key] = shift + + return _LogIndex(runs=runs, clock_shifts=clock_shifts) + + +def _clock_shift_of_clip(key: str, unix_time: int, lon: float) -> int | None: + """ + The seconds to add to the time of the first fix of a clip, at the longitude, + to make it UTC, as the name of the clip tells: the shift that makes the time + of the camera's clock in the name a time zone of the longitude. None if the + name has no time, or no shift makes it one, as when the clock was not set to + the local time + + The clip starts at 12:15 at 8.5°E: a log at 10:15 is UTC (zone UTC+2), and a + log at 02:15 is 8 hours behind it + + >>> _clock_shift_of_clip("no20240601-121500-000123f", 1717236900, 8.5) + 0 + >>> _clock_shift_of_clip("no20240601-121500-000123f", 1717236900 - 8 * 3600, 8.5) + 28800 + >>> _clock_shift_of_clip("no20210101-000000-000123f", 1717236900, 8.5) is None + True + """ + match = _CLIP_CLOCK_PATTERN.match(key) + if match is None: + return None + try: + clock = datetime.datetime.strptime(match.group(1), "%Y%m%d-%H%M%S") + except ValueError: + return None + clock_time = clock.replace(tzinfo=datetime.timezone.utc).timestamp() + + solar_zone_hours = lon / 15 + for shift in _CLOCK_SHIFTS: + zone_hours = (clock_time - (unix_time + shift)) / 3600 + if not (_MIN_ZONE_HOURS <= zone_hours <= _MAX_ZONE_HOURS): + continue + # Across the date line, UTC+13 is 1 hour from the sun's UTC-11 + hours = abs((zone_hours - solar_zone_hours + 12) % 24 - 12) + if hours < _MAX_ZONE_FROM_SOLAR_HOURS: + return shift + return None + + +def _clock_shift(key: str, indices: T.Sequence[_LogIndex]) -> int | None: + """ + The seconds to add to the times of the clip in the logs to make them UTC: as + its name tells, or else as most of the clips in the logs tell. None if they + don't tell, or are split evenly + """ + for index in indices: + if key in index.clock_shifts: + return index.clock_shifts[key] + + votes = collections.Counter( + shift for index in indices for shift in index.clock_shifts.values() + ) + ranked = votes.most_common(2) + if not ranked or (len(ranked) == 2 and ranked[0][1] == ranked[1][1]): + return None + return ranked[0][0] def _clip_key(name: bytes) -> str | None: diff --git a/tests/unit/test_seventymai_log_parser.py b/tests/unit/test_seventymai_log_parser.py index 1152eb7b3..5fa5dd58c 100644 --- a/tests/unit/test_seventymai_log_parser.py +++ b/tests/unit/test_seventymai_log_parser.py @@ -6,6 +6,7 @@ from __future__ import annotations import datetime +import logging import struct from pathlib import Path @@ -48,13 +49,14 @@ def _position(t: int) -> tuple[float, float]: ) -def _row(t: int, clip: str = CLIP, status: str = "A") -> str: +def _row(t: int, clip: str = CLIP, status: str = "A", behind: int = 0) -> str: + # Some cameras log the time "behind" seconds behind UTC lat, lon = _position(t) - return f"{t},{status},{lat:.6f},{lon:.6f},11500,2388,-81,9,40,{clip},0,0,0" + return f"{t - behind},{status},{lat:.6f},{lon:.6f},11500,2388,-81,9,40,{clip},0,0,0" -def _rows(times, clip: str = CLIP) -> list[str]: - return [_row(t, clip) for t in times] +def _rows(times, clip: str = CLIP, behind: int = 0) -> list[str]: + return [_row(t, clip, behind=behind) for t in times] def _no_fix_row(clip: str = CLIP) -> str: @@ -294,6 +296,123 @@ def test_rows_continued_in_the_next_log(tmp_path: Path): assert _extract(video_path) == _expected(CLIP_TIMES, START) +EIGHT_HOURS = 8 * 3600 + + +@pytest.mark.parametrize("behind", [0, EIGHT_HOURS]) +@pytest.mark.parametrize( + "lat, lon, zone", + [ + # Zurich, in summer, as the other tests + (47.3769, 8.5417, 2), + # Santiago de Compostela, in summer, far west of the zone + (42.88, -8.54, 2), + # Kashgar, China, far west of the zone + (39.47, 75.99, 8), + (55.16, 61.40, 5), + (53.90, 27.56, 3), + # New York, in summer + (40.71, -74.01, -4), + (21.31, -157.86, -10), + # Apia, Samoa: across the date line + (-13.83, -171.76, 13), + # Sydney, in winter + (-33.87, 151.21, 10), + ], +) +def test_log_clock(tmp_path: Path, lat: float, lon: float, zone: int, behind: int): + # The file name of the clip has the time of the camera's clock, in local + # time. Some cameras log the GPS time in UTC, others 8 hours behind + clock = datetime.datetime.fromtimestamp( + START + zone * 3600, tz=datetime.timezone.utc + ) + name = clock.strftime("NO%Y%m%d-%H%M%S-000123F.MP4") + video_path = _clip(tmp_path, name=name) + _write( + tmp_path, + [ + f"{t - behind},A,{lat:.6f},{lon:.6f},0,0,0,0,0,{name},0,0,0" + for t in CLIP_TIMES + ], + ) + + points = NativeVideoExtractor(video_path).extract().points + assert [(p.time, p.epoch_time) for p in points] == [ # type: ignore + (float(t - START), float(t)) for t in CLIP_TIMES + ] + + +def test_clip_without_a_clock_takes_that_of_the_other_clips(tmp_path: Path): + # Recorded before the camera set its clock, which started at 2021-01-01 + name = "NO20210101-000512-000123F.MP4" + video_path = _clip(tmp_path, name=name) + _write( + tmp_path, + [ + *_rows(range(START - 60, START, 2), PREVIOUS_CLIP, behind=EIGHT_HOURS), + *_rows(CLIP_TIMES, name, behind=EIGHT_HOURS), + *_rows(range(START + 60, START + 120, 2), NEXT_CLIP, behind=EIGHT_HOURS), + ], + ) + + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + +def test_clip_name_decides_over_the_other_clips(tmp_path: Path): + # Logged in UTC after an update of the camera, after clips logged 8 hours + # behind, in the next log + video_path = _clip(tmp_path) + _write( + tmp_path, + [ + *_rows(range(START - 3600, START - 3540, 2), PREVIOUS_CLIP, EIGHT_HOURS), + *_rows(range(START - 3540, START - 3480, 2), NEXT_CLIP, EIGHT_HOURS), + ], + ) + _write(tmp_path, _rows(CLIP_TIMES), name="GPSData000002.txt") + + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + +@pytest.mark.parametrize( + "lat, lon, clips", + [ + # San Francisco, with the camera's clock in the time of China (UTC+8): + # 16 hours ahead of the log, which is UTC-8 a day later + (37.77, -122.42, ["NO20240601-181500-000123F.MP4"]), + # Zurich: a clip without a clock, and clips that tell opposite clocks + ( + 47.3769, + 8.5417, + [ + "NO20210101-000512-000123F.MP4", + "NO20240601-121400-000122F.MP4", + "NO20240601-041600-000124F.MP4", + ], + ), + ], +) +def test_clock_not_told( + tmp_path: Path, caplog, lat: float, lon: float, clips: list[str] +): + video_path = _clip(tmp_path, name=clips[0]) + times = {clips[0]: CLIP_TIMES} + times.update({clip: [START + 60 * n] for n, clip in enumerate(clips[1:], 1)}) + _write( + tmp_path, + [ + f"{t - EIGHT_HOURS},A,{lat:.6f},{lon:.6f},0,0,0,0,0,{clip},0,0,0" + for clip, clip_times in times.items() + for t in clip_times + ], + ) + + with caplog.at_level(logging.WARNING, logger=seventymai_log_parser.LOG.name): + with pytest.raises(exceptions.MapillaryVideoGPSNotFoundError): + NativeVideoExtractor(video_path).extract() + assert "8 hours behind UTC" in caplog.text + + def test_log_read_once_for_all_its_clips(tmp_path: Path): _write( tmp_path, From 32024c38bfdc9e24b0823e5ecf4049f445b7dbe2 Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Wed, 2 Dec 2026 14:14:43 +0100 Subject: [PATCH 5/8] Take the 2021 placeholder time of a 70mai GPS log as no time Some 70mai cameras write 1609430400, the start of 2021 in China (UTC+8), in the rows they log before they have the time of the GPS, as others write 0 or -28801. Only times of 0 and less were taken as no time, so a row with that time, status A, and a position was a fix from 2021. Before the real fixes of a clip, it made the fixes span years more than the clip, which failed it, and a clip with only such rows got a point dated 2021. Rows with exactly that time are now rows without a fix, so such a clip is placed by its last fix, as with any rows without a fix before the first. --- mapillary_tools/seventymai_log_parser.py | 7 +++++++ tests/unit/test_seventymai_log_parser.py | 13 +++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py index e35187216..fe3d8f723 100644 --- a/mapillary_tools/seventymai_log_parser.py +++ b/mapillary_tools/seventymai_log_parser.py @@ -87,6 +87,10 @@ # they are not of the clip as it is (e.g. a timelapse) _MAX_EXCESS_SECONDS = 5.0 +# The time that some cameras write in the rows before they have the time of the +# GPS: the start of 2021 in China (UTC+8). Others write 0 or -28801 +_PLACEHOLDER_TIME = 1609430400 + # The seconds to add to the times of a log to make them UTC: none, or 8 hours # if the camera takes the UTC time of its GPS for the local time of China _CLOCK_SHIFTS = (0, 8 * 3600) @@ -413,6 +417,8 @@ def _parse_row(line: bytes) -> _Row | None: _Row(fix=None) >>> _parse_row(b"-28801,A,47.376900,8.541700,9000,1250,100,1,-18,NO20240601-121500-000123F.MP4,0,0,0") _Row(fix=None) + >>> _parse_row(b"1609430400,A,47.376900,8.541700,9000,1250,100,1,-18,NO20240601-121500-000123F.MP4,0,0,0") + _Row(fix=None) >>> _parse_row(b"1717236900,A,47.376900,8.5417") is None True """ @@ -430,6 +436,7 @@ def _parse_row(line: bytes) -> _Row | None: if ( fields[1].strip().upper() != b"A" or unix_time <= 0 + or unix_time == _PLACEHOLDER_TIME or not (math.isfinite(lat) and math.isfinite(lon)) or not (-90 <= lat <= 90 and -180 <= lon <= 180) or (lat == 0 and lon == 0) diff --git a/tests/unit/test_seventymai_log_parser.py b/tests/unit/test_seventymai_log_parser.py index 5fa5dd58c..df59ad0b7 100644 --- a/tests/unit/test_seventymai_log_parser.py +++ b/tests/unit/test_seventymai_log_parser.py @@ -215,11 +215,20 @@ def test_first_fix_came_a_few_seconds_late(tmp_path: Path): assert _extract(video_path) == _expected(times, times[0]) -def test_rows_without_a_fix_before_the_first_fix(tmp_path: Path): +@pytest.mark.parametrize( + "no_fix_row", + [ + _no_fix_row(), + # Placeholder times of a position without the time of the GPS + f"1609430400,A,47.376900,8.541700,0,0,0.00,0.00,0.00,{CLIP},0,0,0", + f"-28801,A,47.376900,8.541700,0,0,0,0,0,{CLIP},0,0,0", + ], +) +def test_rows_without_a_fix_before_the_first_fix(tmp_path: Path, no_fix_row: str): # Others write rows without a fix until then video_path = _clip(tmp_path) times = [t for t in CLIP_TIMES if START + 3 <= t] - _write(tmp_path, [_no_fix_row(), _no_fix_row(), *_rows(times)]) + _write(tmp_path, [no_fix_row, no_fix_row, *_rows(times)]) assert _extract(video_path) == _expected(times, times[-1] - 60.0) From 862735afe90fb2e3f3e71595403bc6ea79a84ed4 Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Wed, 2 Dec 2026 14:14:57 +0100 Subject: [PATCH 6/8] Don't take a 70mai clip name that may be China time as telling the log's clock MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The name of a clip tells whether the GPS log is UTC or 8 hours behind only if the camera's clock is set to local time. A clock set to the time of China (UTC+8), as the placeholder times of the logs are, with a log in UTC reads exactly as a log 8 hours behind in a zone at UTC+0. That zone fits the sun from about 60°W to 60°E, so the clips of such a camera in Europe, Africa or South America got times 8 hours late. That reading no longer counts. A clip that gives only it takes the clock that the other clips in the logs tell, or else fails with the warning that the log can't be told. That includes a log 8 hours behind in a real zone at UTC+0 (the UK and Portugal in winter, Iceland, West Africa), unless clips of the same camera at another offset, such as in summer, tell it. The mirror case can't be guarded: a clock set to UTC with a log 8 hours behind reads as a log in UTC in a zone at UTC+8, as in China, and gets times 8 hours early. The docstring, the README and the command reference now say that the camera's clock must be set to local time, and give both limits. --- README.md | 3 +- docs/command_reference.md | 6 +++- mapillary_tools/seventymai_log_parser.py | 35 ++++++++++++++++++------ tests/unit/test_seventymai_log_parser.py | 35 +++++++++++++++++++++--- 4 files changed, 65 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 0fef00962..cb7a39823 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,8 @@ mapillary_tools supports videos (.mp4, .360) that contain any of the following t - [DR900S-1CH](https://shop.blackvue.com/product/dr900x-1ch-plus/) - [DR900X Plus](https://shop.blackvue.com/product/dr900x-2ch-plus/) - Novatek-based dashcams, such as Viofo, Vantrue and Anker Roav dashcams -- 70mai dashcams, from the GPS log (`GPSData000001.txt`) that they write beside the videos: keep it in the same folder +- 70mai dashcams, from the GPS log (`GPSData000001.txt`) that they write beside the videos: keep it in the same folder, + and set the camera's clock to local time (see the command reference) Other videos can be geotagged from the GPS that [ExifTool](https://exiftool.org/) reads, if it is installed, or from a GPX or NMEA track recorded along with them (see [Geotagging with GPX](#geotagging-with-gpx)). diff --git a/docs/command_reference.md b/docs/command_reference.md index c7a96039c..a4daec04a 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -215,7 +215,7 @@ Repeat the option or separate sources with commas. The default is `native`, then | Source | Images | Videos | | ------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------ | -| `native` | EXIF | The GPS of the video: GoPro (GPMF), CAMM, BlackVue, and Novatek-based dashcams; for a 70mai dashcam, its GPS log (`GPSData*.txt`) in the folder of the video | +| `native` | EXIF | The GPS of the video: GoPro (GPMF), CAMM, BlackVue, and Novatek-based dashcams; for a 70mai dashcam, its GPS log (`GPSData*.txt`) in the folder of the video (see below) | | `exif` | EXIF | Cannot read videos | | `exiftool_runtime` (`exiftool`) | Runs ExifTool on the image | Runs ExifTool on the video | | `exiftool_xml` | Reads the output of `exiftool -X`, by default `%g.xml` beside the file | The same | @@ -241,6 +241,10 @@ Gotchas: videos, and a source limited with `"filetypes": ["image"]` leaves the videos without one. - `gpx` and `nmea` for images need a single track file, given with `--geotag_source_path`. Without it, the command stops (exit code 2) when an image reaches the source. +- The GPS log of a 70mai dashcam is in UTC on some cameras and 8 hours behind UTC on others. The names of the + clips, which have the time of the camera's clock, tell which, if that clock is set to local time. A clip whose + log can't be told fails with a warning. A clock set to UTC with a log 8 hours behind is taken as a log in UTC + in a zone at UTC+8, so the clips get times 8 hours early. ### --video_geotag_source diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py index fe3d8f723..95e8aca0a 100644 --- a/mapillary_tools/seventymai_log_parser.py +++ b/mapillary_tools/seventymai_log_parser.py @@ -21,13 +21,22 @@ The Unix time is UTC on some cameras, and 8 hours behind UTC on others, whose firmware takes the UTC time of the GPS for the local time of China (UTC+8). The -file name of a clip tells which: it is the time of the camera's clock at the start -of the clip, in local time, so the difference from the time of its first fix is -the time zone where it was recorded, once the log's time is UTC. Time zones are -within about 3 hours of the solar time of their longitude, and the two clocks are -8 hours apart, so at most one gives a zone that fits. A clip whose name fits -neither, as when the camera's clock was not set, takes the clock that most of the -other clips in the logs fit. If none fits, the log is not used. +file name of a clip tells which, if the camera's clock is set to local time: it is +the time of that clock at the start of the clip, so the difference from the time +of its first fix is the time zone where it was recorded, once the log's time is +UTC. Time zones are within about 3 hours of the solar time of their longitude, and +the two clocks are 8 hours apart, so at most one gives a zone that fits. A clip +whose name fits neither, as when the camera's clock was not set, takes the clock +that most of the other clips in the logs fit. If none fits, the log is not used. + +A clock that is not set to local time can fit the wrong one. Set to the time of +China, as the camera's placeholder times are (the start of 2021 in China), with a +log in UTC, it reads as a log 8 hours behind in a zone at UTC+0, which fits from +about 60°W to 60°E. So that reading is not counted: such a clip takes the clock of +the other clips, if they tell. A log 8 hours behind in a zone at UTC+0 (the UK in +winter, Iceland, West Africa) is not told by its own clip names either. A clock in +UTC with a log 8 hours behind reads as a log in UTC in a zone at UTC+8, which can't +be told from a log in UTC in China (UTC+8): it is taken as such, 8 hours early. The rows carry the GPS time of the fixes, not their time in the video. A camera that has a fix when a clip starts, as in the middle of a recording, writes the first @@ -102,6 +111,10 @@ _MIN_ZONE_HOURS = -12.0 _MAX_ZONE_HOURS = 14.0 +# A clock in the time of China (UTC+8) with a log in UTC reads as a log 8 hours +# behind in a zone at UTC+0, give or take the drift of the clock +_MAX_DRIFT_HOURS = 0.5 + # The time of the camera's clock at the start of a clip, in its file name # (NO20240601-121500-000123F.MP4) _CLIP_CLOCK_PATTERN = re.compile(r"[a-z]*(\d{8}-\d{6})(?!\d)") @@ -334,7 +347,8 @@ def _clock_shift_of_clip(key: str, unix_time: int, lon: float) -> int | None: to make it UTC, as the name of the clip tells: the shift that makes the time of the camera's clock in the name a time zone of the longitude. None if the name has no time, or no shift makes it one, as when the clock was not set to - the local time + the local time, or only 8 hours does, with a zone at UTC+0, as a clock in the + time of China does with a log in UTC The clip starts at 12:15 at 8.5°E: a log at 10:15 is UTC (zone UTC+2), and a log at 02:15 is 8 hours behind it @@ -345,6 +359,8 @@ def _clock_shift_of_clip(key: str, unix_time: int, lon: float) -> int | None: 28800 >>> _clock_shift_of_clip("no20210101-000000-000123f", 1717236900, 8.5) is None True + >>> _clock_shift_of_clip("no20240601-181500-000123f", 1717236900, 8.5) is None + True """ match = _CLIP_CLOCK_PATTERN.match(key) if match is None: @@ -360,6 +376,9 @@ def _clock_shift_of_clip(key: str, unix_time: int, lon: float) -> int | None: zone_hours = (clock_time - (unix_time + shift)) / 3600 if not (_MIN_ZONE_HOURS <= zone_hours <= _MAX_ZONE_HOURS): continue + if shift and abs(zone_hours) < _MAX_DRIFT_HOURS: + # As likely a clock in the time of China with a log in UTC + continue # Across the date line, UTC+13 is 1 hour from the sun's UTC-11 hours = abs((zone_hours - solar_zone_hours + 12) % 24 - 12) if hours < _MAX_ZONE_FROM_SOLAR_HOURS: diff --git a/tests/unit/test_seventymai_log_parser.py b/tests/unit/test_seventymai_log_parser.py index df59ad0b7..db377c599 100644 --- a/tests/unit/test_seventymai_log_parser.py +++ b/tests/unit/test_seventymai_log_parser.py @@ -384,15 +384,21 @@ def test_clip_name_decides_over_the_other_clips(tmp_path: Path): @pytest.mark.parametrize( - "lat, lon, clips", + "lat, lon, behind, clips", [ # San Francisco, with the camera's clock in the time of China (UTC+8): # 16 hours ahead of the log, which is UTC-8 a day later - (37.77, -122.42, ["NO20240601-181500-000123F.MP4"]), + (37.77, -122.42, EIGHT_HOURS, ["NO20240601-181500-000123F.MP4"]), + # Zurich, with the camera's clock in the time of China and a log in + # UTC: as a log 8 hours behind in a zone at UTC+0 + (47.3769, 8.5417, 0, ["NO20240601-181500-000123F.MP4"]), + # London in winter (UTC+0), with a log 8 hours behind: the same + (51.51, -0.13, EIGHT_HOURS, ["NO20240601-101500-000123F.MP4"]), # Zurich: a clip without a clock, and clips that tell opposite clocks ( 47.3769, 8.5417, + EIGHT_HOURS, [ "NO20210101-000512-000123F.MP4", "NO20240601-121400-000122F.MP4", @@ -402,7 +408,7 @@ def test_clip_name_decides_over_the_other_clips(tmp_path: Path): ], ) def test_clock_not_told( - tmp_path: Path, caplog, lat: float, lon: float, clips: list[str] + tmp_path: Path, caplog, lat: float, lon: float, behind: int, clips: list[str] ): video_path = _clip(tmp_path, name=clips[0]) times = {clips[0]: CLIP_TIMES} @@ -410,7 +416,7 @@ def test_clock_not_told( _write( tmp_path, [ - f"{t - EIGHT_HOURS},A,{lat:.6f},{lon:.6f},0,0,0,0,0,{clip},0,0,0" + f"{t - behind},A,{lat:.6f},{lon:.6f},0,0,0,0,0,{clip},0,0,0" for clip, clip_times in times.items() for t in clip_times ], @@ -422,6 +428,27 @@ def test_clock_not_told( assert "8 hours behind UTC" in caplog.text +def test_clip_at_utc_0_takes_the_clock_of_the_other_clips(tmp_path: Path): + # Recorded at UTC+0 (as in the UK in winter), with a log 8 hours behind, + # which its name does not tell: the other clips in the log, at UTC+1 (as in + # summer), do + name = "NO20240601-101500-000123F.MP4" + video_path = _clip(tmp_path, name=name) + summer_clips = ["NO20240601-111400-000122F.MP4", "NO20240601-111600-000124F.MP4"] + _write( + tmp_path, + [ + *_rows(CLIP_TIMES, name, behind=EIGHT_HOURS), + *[ + _row(START + 60 * n, clip, behind=EIGHT_HOURS) + for n, clip in enumerate(summer_clips, 1) + ], + ], + ) + + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + def test_log_read_once_for_all_its_clips(tmp_path: Path): _write( tmp_path, From dcf7afda700cd5bbcd892dfd5d347f348dab953a Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Wed, 2 Dec 2026 14:31:03 +0100 Subject: [PATCH 7/8] Say that a 70mai clock in UTC with a log 8 hours behind fails, but in Asia MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The docstring and the command reference said that a camera clock set to UTC with a log 8 hours behind is always taken as a log in UTC in a zone at UTC+8, 8 hours early. That reading fits only where UTC+8 fits the sun, from about 60°E to 180°E. Elsewhere it reads as a log 8 hours behind in a zone at UTC+0, which is no longer counted, so the clip fails with the warning, as in Zurich. --- docs/command_reference.md | 4 ++-- mapillary_tools/seventymai_log_parser.py | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/command_reference.md b/docs/command_reference.md index a4daec04a..b6b9cee25 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -243,8 +243,8 @@ Gotchas: command stops (exit code 2) when an image reaches the source. - The GPS log of a 70mai dashcam is in UTC on some cameras and 8 hours behind UTC on others. The names of the clips, which have the time of the camera's clock, tell which, if that clock is set to local time. A clip whose - log can't be told fails with a warning. A clock set to UTC with a log 8 hours behind is taken as a log in UTC - in a zone at UTC+8, so the clips get times 8 hours early. + log can't be told fails with a warning, as do the clips of a clock set to UTC with a log 8 hours behind, except + from about 60°E to 180°E: there they are taken as a log in UTC in a zone at UTC+8, and get times 8 hours early. ### --video_geotag_source diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py index 95e8aca0a..073f422e3 100644 --- a/mapillary_tools/seventymai_log_parser.py +++ b/mapillary_tools/seventymai_log_parser.py @@ -35,8 +35,10 @@ about 60°W to 60°E. So that reading is not counted: such a clip takes the clock of the other clips, if they tell. A log 8 hours behind in a zone at UTC+0 (the UK in winter, Iceland, West Africa) is not told by its own clip names either. A clock in -UTC with a log 8 hours behind reads as a log in UTC in a zone at UTC+8, which can't -be told from a log in UTC in China (UTC+8): it is taken as such, 8 hours early. +UTC with a log 8 hours behind reads as a log 8 hours behind in a zone at UTC+0, +which is not counted, or as a log in UTC in a zone at UTC+8, which fits only from +about 60°E to 180°E. So it is not told, except there: it can't be told from a log +in UTC in China (UTC+8), and is taken as such, 8 hours early. The rows carry the GPS time of the fixes, not their time in the video. A camera that has a fix when a clip starts, as in the middle of a recording, writes the first From 45222fd628326767e53bf7d70c237d47f72f9838 Mon Sep 17 00:00:00 2001 From: Caglar Pir Date: Wed, 2 Dec 2026 14:09:41 +0100 Subject: [PATCH 8/8] Read the GPS of a 70mai rear camera clip from the rows of its front clip The GPS logs of 70mai dashcams name only the clips of the front camera (NO20250209-170040-000944F.MP4): all 5,223 clips named in three sample logs end with F. So a clip of the rear camera found no rows and got no GPS. A clip that the logs don't name now takes the rows of the clip they do name with the same name but for the letter of the camera at its end, as the two cameras start their clips together: ...000944B takes the rows of ...000944F. It matches only if the start time and the number are the same, and the logs name exactly one such clip. A clip with rows of its own keeps them. The rows are placed in the clip by its own duration, and their clock is told by the name of the front clip, as for the front clip itself. The README says to keep the log, or a copy of it, beside the rear videos too. No sample has a rear clip, so its name is inferred from the front clip's letter (F) rather than seen: the match takes any letter in its place. --- README.md | 5 +- mapillary_tools/seventymai_log_parser.py | 91 ++++++++++++++++++++++-- tests/unit/test_seventymai_log_parser.py | 46 ++++++++++++ 3 files changed, 134 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index cb7a39823..4681b8e29 100644 --- a/README.md +++ b/README.md @@ -104,8 +104,9 @@ mapillary_tools supports videos (.mp4, .360) that contain any of the following t - [DR900S-1CH](https://shop.blackvue.com/product/dr900x-1ch-plus/) - [DR900X Plus](https://shop.blackvue.com/product/dr900x-2ch-plus/) - Novatek-based dashcams, such as Viofo, Vantrue and Anker Roav dashcams -- 70mai dashcams, from the GPS log (`GPSData000001.txt`) that they write beside the videos: keep it in the same folder, - and set the camera's clock to local time (see the command reference) +- 70mai dashcams, from the GPS log (`GPSData000001.txt`) that they write beside the videos: keep it in the folder of the + videos, or a copy of it in each folder of videos, front and rear, and set the camera's clock to local time (see the + command reference) Other videos can be geotagged from the GPS that [ExifTool](https://exiftool.org/) reads, if it is installed, or from a GPX or NMEA track recorded along with them (see [Geotagging with GPX](#geotagging-with-gpx)). diff --git a/mapillary_tools/seventymai_log_parser.py b/mapillary_tools/seventymai_log_parser.py index 073f422e3..fc0989221 100644 --- a/mapillary_tools/seventymai_log_parser.py +++ b/mapillary_tools/seventymai_log_parser.py @@ -40,6 +40,11 @@ about 60°E to 180°E. So it is not told, except there: it can't be told from a log in UTC in China (UTC+8), and is taken as such, 8 hours early. +The rows name the clips of the front camera (NO20240601-121500-000123F.MP4). A clip +of another camera, such as the rear one (...000123B.MP4), is recorded with the front +clip of the same name but for the letter of its camera, so it takes the rows of +that clip if the logs name no clip of its own. + The rows carry the GPS time of the fixes, not their time in the video. A camera that has a fix when a clip starts, as in the middle of a recording, writes the first row of the clip within about a second of its start, and the last within a few @@ -121,6 +126,10 @@ # (NO20240601-121500-000123F.MP4) _CLIP_CLOCK_PATTERN = re.compile(r"[a-z]*(\d{8}-\d{6})(?!\d)") +# A clip name (casefolded) that ends with the letter of its camera, after its +# number: F for the front camera +_CAMERA_LETTER_PATTERN = re.compile(r"([a-z]*\d{8}-\d{6}-\d+)[a-z]") + class _Row(T.NamedTuple): # (Unix time, latitude, longitude), or None if the row is not a valid fix @@ -134,6 +143,9 @@ class _LogIndex(T.NamedTuple): # The seconds to add to the times of each clip to make them UTC, as its # file name tells (see _clock_shift_of_clip), for the clips whose name tells clock_shifts: dict[str, int] + # The clips by their name without the letter of their camera (see + # _front_clip_key) + clips_by_name: dict[str, list[str]] def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: @@ -154,21 +166,40 @@ def extract_points(video_path: Path) -> list[telemetry.GPSPoint] | None: if not log_paths: return None + logs: list[tuple[Path, _LogIndex]] = [] + for log_path in log_paths: + try: + logs.append((log_path, _load_index(log_path))) + except OSError as ex: + LOG.warning("Unable to read the GPS log %s: %s", log_path, ex) + indices = [index for _, index in logs] + + key = video_path.stem.casefold() + if not any(key in index.runs for index in indices): + # The logs name the clips of the front camera only: a clip of another + # camera takes the rows of the front clip that started with it + front_key = _front_clip_key(key, indices) + if front_key is None: + LOG.debug("No rows of %s in the GPS logs %s", video_path.name, log_paths) + return None + LOG.debug( + "Reading the GPS of %s from the rows of %s in the GPS logs", + video_path.name, + front_key, + ) + key = front_key + # The rows of the clip in the order the camera wrote them, which may be # continued in the next log, and whether they are the first rows that the # camera wrote after it started logging - key = video_path.stem.casefold() rows: list[_Row] = [] first_logged: bool | None = None - indices: list[_LogIndex] = [] - for log_path in log_paths: + for log_path, index in logs: try: - index = _load_index(log_path) clip_rows, begins = _read_clip_rows(log_path, index, key) except OSError as ex: LOG.warning("Unable to read the GPS log %s: %s", log_path, ex) continue - indices.append(index) if first_logged is None and begins is not None: first_logged = begins == _AFTER_HEADER rows.extend(clip_rows) @@ -340,7 +371,13 @@ def _index_log(log_path: Path, size: int, mtime_ns: int) -> _LogIndex: if shift is not None: clock_shifts[key] = shift - return _LogIndex(runs=runs, clock_shifts=clock_shifts) + clips_by_name: dict[str, list[str]] = {} + for key in runs: + unlettered = _clip_name_without_camera(key) + if unlettered is not None: + clips_by_name.setdefault(unlettered, []).append(key) + + return _LogIndex(runs=runs, clock_shifts=clock_shifts, clips_by_name=clips_by_name) def _clock_shift_of_clip(key: str, unix_time: int, lon: float) -> int | None: @@ -388,6 +425,48 @@ def _clock_shift_of_clip(key: str, unix_time: int, lon: float) -> int | None: return None +def _front_clip_key(key: str, indices: T.Sequence[_LogIndex]) -> str | None: + """ + The clip in the logs that has the name of the clip but for the letter of its + camera at the end (F for the front camera), as the logs name the clips of the + front camera only. None if the logs name no such clip, or more than one + + >>> index = _LogIndex( + ... runs={"no20240601-121500-000123f": []}, + ... clock_shifts={}, + ... clips_by_name={"no20240601-121500-000123": ["no20240601-121500-000123f"]}, + ... ) + >>> _front_clip_key("no20240601-121500-000123b", [index]) + 'no20240601-121500-000123f' + >>> _front_clip_key("no20240601-121501-000123b", [index]) is None + True + """ + name = _clip_name_without_camera(key) + if name is None: + return None + candidates = { + other + for index in indices + for other in index.clips_by_name.get(name, ()) + if other != key + } + return candidates.pop() if len(candidates) == 1 else None + + +def _clip_name_without_camera(key: str) -> str | None: + """ + The name of a clip without the letter of its camera at its end, or None if + the name does not end with one + + >>> _clip_name_without_camera("no20240601-121500-000123f") + 'no20240601-121500-000123' + >>> _clip_name_without_camera("clip") is None + True + """ + match = _CAMERA_LETTER_PATTERN.fullmatch(key) + return None if match is None else match.group(1) + + def _clock_shift(key: str, indices: T.Sequence[_LogIndex]) -> int | None: """ The seconds to add to the times of the clip in the logs to make them UTC: as diff --git a/tests/unit/test_seventymai_log_parser.py b/tests/unit/test_seventymai_log_parser.py index db377c599..82f7d7e87 100644 --- a/tests/unit/test_seventymai_log_parser.py +++ b/tests/unit/test_seventymai_log_parser.py @@ -295,6 +295,52 @@ def test_clip_names(tmp_path: Path, logged_name: str): assert _extract(video_path) == _expected(CLIP_TIMES, START) +REAR_CLIP = "NO20240601-121500-000123B.MP4" + + +@pytest.mark.parametrize("logged_name", [CLIP, "NO20240601-121500-000123F.MP44"]) +def test_rear_clip_takes_the_rows_of_the_front_clip(tmp_path: Path, logged_name: str): + # The logs name the clips of the front camera only + video_path = _clip(tmp_path, name=REAR_CLIP) + _write( + tmp_path, + [ + *_rows(range(START - 60, START, 2), PREVIOUS_CLIP), + *_rows(CLIP_TIMES, logged_name), + *_rows(range(START + 60, START + 120, 2), NEXT_CLIP), + ], + ) + + assert _extract(video_path) == _expected(CLIP_TIMES, START) + + +def test_clip_with_rows_of_its_own_takes_them(tmp_path: Path): + video_path = _clip(tmp_path, name=REAR_CLIP) + rear_times = [t for t in CLIP_TIMES if t <= START + 30] + _write(tmp_path, [*_rows(CLIP_TIMES), *_rows(rear_times, REAR_CLIP)]) + + assert _extract(video_path) == _expected(rear_times, START) + + +@pytest.mark.parametrize( + "logged_names", + [ + # Started a second later + ["NO20240601-121501-000123F.MP4"], + # Another number + ["NO20240601-121500-000124F.MP4"], + # Two clips of other cameras + [CLIP, "NO20240601-121500-000123I.MP4"], + ], +) +def test_rear_clip_without_one_front_clip(tmp_path: Path, logged_names: list[str]): + video_path = _clip(tmp_path, name=REAR_CLIP) + _write(tmp_path, [row for name in logged_names for row in _rows(CLIP_TIMES, name)]) + + with pytest.raises(exceptions.MapillaryVideoGPSNotFoundError): + NativeVideoExtractor(video_path).extract() + + def test_rows_continued_in_the_next_log(tmp_path: Path): video_path = _clip(tmp_path) _write(tmp_path, _rows(CLIP_TIMES[:10]), name="GPSData000001.txt")