diff --git a/README.md b/README.md index 8c27fe22..4681b8e2 100644 --- a/README.md +++ b/README.md @@ -104,6 +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 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/docs/command_reference.md b/docs/command_reference.md index 97fc21e8..b6b9cee2 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 (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, 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/geotag/video_extractors/native.py b/mapillary_tools/geotag/video_extractors/native.py index 17716870..06dcb8db 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 00000000..fc098922 --- /dev/null +++ b/mapillary_tools/seventymai_log_parser.py @@ -0,0 +1,562 @@ +# 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 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, 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 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 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 +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 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 + +import collections +import datetime +import functools +import logging +import math +import os +import re +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 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), 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" +_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) +_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) + +# 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 + +# 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)") + +# 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 + 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] + # 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: + """ + 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, 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: + 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 + + 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 + rows: list[_Row] = [] + first_logged: bool | None = None + for log_path, index in logs: + try: + 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 + if first_logged is None and begins is not None: + first_logged = begins == _AFTER_HEADER + rows.extend(clip_rows) + + 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 + + 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 + ): + # 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 + clock_shift), + 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 _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 + """ + runs = index.runs.get(key) + if not runs: + return [], None + + rows: list[_Row] = [] + with log_path.open("rb") as fp: + 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, runs[0][2] + + +@functools.lru_cache(maxsize=16) +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, 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 + """ + 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: + 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) + if run_key is not None: + runs.setdefault(run_key, []).append((run_start, offset, run_where)) + + 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 + + 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: + """ + 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, 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 + + >>> _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 + >>> _clock_shift_of_clip("no20240601-181500-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 + 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: + return shift + 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 + 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: + """ + 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"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 + """ + 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 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) + ): + 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 00000000..82f7d7e8 --- /dev/null +++ b/tests/unit/test_seventymai_log_parser.py @@ -0,0 +1,564 @@ +# 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 logging +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", behind: int = 0) -> str: + # Some cameras log the time "behind" seconds behind UTC + lat, lon = _position(t) + return f"{t - behind},{status},{lat:.6f},{lon:.6f},11500,2388,-81,9,40,{clip},0,0,0" + + +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: + # 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", + 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: + 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 + + +@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, [*before, *_rows(times)]) + + # The last fix marks the end of the clip + assert _extract(video_path) == _expected(times, times[-1] - 60.0) + + +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[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) + times = [t for t in CLIP_TIMES if START + 6 <= t] + _write(tmp_path, _rows(times)) + + assert _extract(video_path) == _expected(times, times[0]) + + +@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)]) + + 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) + + +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") + _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) + + +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, 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, 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", + "NO20240601-041600-000124F.MP4", + ], + ), + ], +) +def test_clock_not_told( + 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} + times.update({clip: [START + 60 * n] for n, clip in enumerate(clips[1:], 1)}) + _write( + tmp_path, + [ + 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 + ], + ) + + 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_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, + [*_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]