diff --git a/docs/command_reference.md b/docs/command_reference.md index db367eda..3dac7241 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -358,8 +358,11 @@ How a track is lined up with a video: then fail, and only logs the refusal as a warning. `--interpolation_use_gpx_start_time` refuses such a track too. - `process` uploads a long track with the warning, as that of a timelapse, but refuses a track of a day or more (a log of several trips) unless the video lasts more than half as long. -- In `video_process`, give a timelapse without GPS of its own `--video_duration_ratio`: the seconds of capture - per second of video, such as 60 for one frame every 2 seconds played at 30 frames per second. +- In `video_process`, give a timelapse without a GPS clock of its own (no GPS, or GPS positions without + timestamps) `--video_duration_ratio`: the seconds of capture per second of video, such as 60 for one frame + every 2 seconds played at 30 frames per second. It paces the capture times of the frames, in interval and in + distance sampling, and for a camera that stamps its creation time at the end of the recording, it places the + start that many times the video's duration before it. ### ExifTool diff --git a/mapillary_tools/sample_video.py b/mapillary_tools/sample_video.py index 43ba6e64..49506d27 100644 --- a/mapillary_tools/sample_video.py +++ b/mapillary_tools/sample_video.py @@ -679,7 +679,7 @@ def _is_end_stamping_camera(video_path: Path, probe: ffmpeglib.Probe) -> bool: def _creation_time_to_start_time( - video_path: Path, probe: ffmpeglib.Probe + video_path: Path, probe: ffmpeglib.Probe, duration_ratio: float = 1.0 ) -> datetime.datetime | None: """ Determine the wall clock time at which a video started recording from the @@ -692,6 +692,10 @@ def _creation_time_to_start_time( metadata says which, so look for evidence: a camera known to stamp the end, or a time in the file name that matches only one of the two. Without any, assume the start and warn about the alternative. + + The end of a timelapse is as many seconds after its start as it took to + record, which is **duration_ratio** (--video_duration_ratio) times as long + as the video plays. """ creation_time = probe.probe_video_creation_time() if creation_time is None: @@ -706,7 +710,11 @@ def _creation_time_to_start_time( ) return creation_time - start_time_if_end_stamped = creation_time - datetime.timedelta(seconds=duration) + # The seconds it took to record the video + recording_seconds = duration * duration_ratio + start_time_if_end_stamped = creation_time - datetime.timedelta( + seconds=recording_seconds + ) if _is_end_stamping_camera(video_path, probe): return start_time_if_end_stamped @@ -728,7 +736,7 @@ def _creation_time_to_start_time( "specify --video_start_time %s to use that", creation_time, video_path.name, - duration, + recording_seconds, build_capture_time(start_time_if_end_stamped), ) return creation_time @@ -738,6 +746,7 @@ def _extract_video_start_time( video_path: Path, probe: ffmpeglib.Probe, telemetry_points: T.Sequence[geo.Point], + duration_ratio: float = 1.0, ) -> datetime.datetime | None: """ Determine the wall clock time at which a video started recording. @@ -748,13 +757,14 @@ def _extract_video_start_time( back to the creation time when there is no telemetry to sync against. It then only labels the samples: their positions come from the video's own GPS, and a GPX or NMEA track that geotags them places them by its own start - instead (see _track_file_start_time). + instead (see _track_file_start_time). The creation time of a timelapse is + read at **duration_ratio** (--video_duration_ratio). """ start_time = _gps_clock_start_time(telemetry_points) if start_time is not None: return start_time - return _creation_time_to_start_time(video_path, probe) + return _creation_time_to_start_time(video_path, probe, duration_ratio) # The sources that place a track file on a video, by the extractor that reads it @@ -1004,7 +1014,7 @@ def _sample_single_video_by_interval( elif start_time is None: start_time = _track_file_start_time( video_path, geotag_options, video_sync - ) or _extract_video_start_time(video_path, probe, telemetry_points) + ) or _extract_video_start_time(video_path, probe, telemetry_points, rate) if start_time is None: raise exceptions.MapillaryVideoError( f"Unable to extract video start time from {video_path}" @@ -1800,7 +1810,7 @@ def _sample_single_video_by_distance( ): start_time = _gps_clock_start_time(video_metadata.points) if start_time is None: - start_time = _creation_time_to_start_time(video_path, probe) + start_time = _creation_time_to_start_time(video_path, probe, duration_ratio) if start_time is None: raise exceptions.MapillaryVideoError( f"Unable to extract video start time from {video_path}" @@ -1856,8 +1866,12 @@ def _sample_single_video_by_distance( gps_unix_time, tz=datetime.timezone.utc ) else: + # Without a GPS clock, a timelapse is paced by + # --video_duration_ratio, as interval samples are assert start_time is not None - timestamp = start_time + datetime.timedelta(seconds=interp.time) + timestamp = start_time + datetime.timedelta( + seconds=interp.time * duration_ratio + ) exif_edit = ExifEdit(sample_paths[0]) exif_edit.add_date_time_original(timestamp) exif_edit.add_gps_datetime(timestamp) diff --git a/tests/unit/test_sample_video.py b/tests/unit/test_sample_video.py index 373578eb..f05e54c1 100644 --- a/tests/unit/test_sample_video.py +++ b/tests/unit/test_sample_video.py @@ -539,6 +539,36 @@ def test_the_duration_ratio_paces_a_video_without_a_gps_clock( seconds_per_sample=10, ) + def test_the_duration_ratio_places_the_start_of_an_end_stamping_camera( + self, tmpdir, setup_mock + ): + """ + A camera that stamps the creation time at the end of the recording + stamps a timelapse as long after its start as it took to record + """ + probe = json.loads( + _PWD.joinpath("data/mock_sample_video/videos/hello.mp4").read_text() + ) + probe["format"]["tags"].update(make="RICOH", model="RICOH THETA X") + video_dir = tmpdir.mkdir("videos") + video_dir.join("hello.mp4").write(json.dumps(probe)) + sample_dir = tmpdir.mkdir("sampled_video_frames") + sample_video.sample_video( + Path(video_dir), + Path(sample_dir), + video_sample_distance=-1, + video_sample_interval=2, + rerun=True, + video_duration_ratio=5, + ) + + probe_duration = float(probe["streams"][0]["duration"]) + _validate_interval( + [Path(s) for s in sample_dir.join("hello.mp4").listdir()], + PROBE_START_TIME - datetime.timedelta(seconds=5 * probe_duration), + seconds_per_sample=10, + ) + class TestLocateIntervalSamples: """ @@ -1577,6 +1607,35 @@ def test_known_end_stamping_camera(self, tmp_path: Path) -> None: == self.START_TIME_IF_END_STAMPED ) + def test_known_end_stamping_camera_timelapse(self, tmp_path: Path) -> None: + # At 10x, the 60-second video took 10 minutes to record + video_path = self._video(tmp_path, "R0020627.MP4") + probe = self._probe(format_tags={"make": "RICOH", "model": "RICOH THETA X"}) + assert sample_video._creation_time_to_start_time( + video_path, probe, duration_ratio=10 + ) == self.CREATION_TIME - datetime.timedelta(minutes=10) + + def test_file_name_matches_end_of_timelapse(self, tmp_path: Path) -> None: + # Named by its start in local time (UTC+9), 10 minutes before the + # creation time at 10x, which only the ratio makes a match + video_path = self._video(tmp_path, "2023_0307_102634_0001F.MP4") + assert sample_video._creation_time_to_start_time( + video_path, self._probe(), duration_ratio=10 + ) == self.CREATION_TIME - datetime.timedelta(minutes=10) + + def test_assumes_start_of_timelapse_without_evidence( + self, tmp_path: Path, caplog + ) -> None: + video_path = self._video(tmp_path, "clip.mp4") + with caplog.at_level(logging.WARNING, logger=sample_video.LOG.name): + start_time = sample_video._creation_time_to_start_time( + video_path, self._probe(), duration_ratio=10 + ) + assert start_time == self.CREATION_TIME + # The start it suggests is the recording time before, not the video's + assert "started 600.0 seconds earlier" in caplog.text + assert "--video_start_time 2023_03_07_01_26_34_000" in caplog.text + def test_other_models_of_the_same_make(self, tmp_path: Path) -> None: video_path = self._video(tmp_path, "R0010001.MP4") probe = self._probe(format_tags={"make": "RICOH", "model": "RICOH THETA Z1"}) @@ -2095,9 +2154,13 @@ def _setup_mocks( sample_times: T.Sequence[float] | None = None, # The index of the source that reads the track, of those tried read_by: int = 0, + # Container tags to add to the probe, such as make and model + format_tags: dict[str, str] | None = None, ) -> dict[str, T.Any]: """Set up all the mocks needed for _sample_single_video_by_distance.""" probe_output = _load_probe_output() + if format_tags: + probe_output["format"]["tags"].update(format_tags) if gps_points is None: gps_points = _make_gps_points(num_gps_points, time_step=1.0) num_gps_points = len(gps_points) @@ -2408,6 +2471,79 @@ def test_timestamps_from_creation_time(self, tmp_path: Path) -> None: PROBE_START_TIME + datetime.timedelta(seconds=idx) ) + def _sample_timelapse( + self, tmp_path: Path, format_tags: dict[str, str] | None = None, **kwargs + ) -> list[datetime.datetime | None]: + """ + Sample a video whose track has positions without timestamps, one point + per second of video, by distance, and return the capture times of the + frames + """ + video_dir = tmp_path / "videos" + video_dir.mkdir() + video_file = video_dir / "test.mp4" + video_file.touch() + output_dir = tmp_path / "output" + + mocks = self._setup_mocks(tmp_path, video_file, format_tags=format_tags) + + with ( + mocks["patches"]["ffmpeg_cls"], + mocks["patches"]["geotag_cls"], + mocks["patches"]["moov_parse"], + ): + sample_video.sample_video( + video_import_path=video_file, + import_path=output_dir, + video_sample_distance=0.0, + **kwargs, + ) + + frames = sorted((output_dir / "test.mp4").glob("*.jpg")) + assert len(frames) == 10 + return [exif_read.ExifRead(frame).extract_capture_time() for frame in frames] + + def test_timestamps_from_creation_time_at_the_duration_ratio( + self, tmp_path: Path, caplog + ) -> None: + """ + Without a GPS clock, the frames of a timelapse are paced by + --video_duration_ratio, as interval samples are + """ + with caplog.at_level(logging.WARNING): + capture_times = self._sample_timelapse(tmp_path, video_duration_ratio=10) + assert capture_times == [ + PROBE_START_TIME + datetime.timedelta(seconds=10 * idx) for idx in range(10) + ] + assert "Ignoring --video_duration_ratio" not in caplog.text + + def test_given_start_time_at_the_duration_ratio(self, tmp_path: Path) -> None: + capture_times = self._sample_timelapse( + tmp_path, + video_start_time="2023_06_15_12_00_00_000", + video_duration_ratio=10, + ) + start_time = datetime.datetime(2023, 6, 15, 12, tzinfo=datetime.timezone.utc) + assert capture_times == [ + start_time + datetime.timedelta(seconds=10 * idx) for idx in range(10) + ] + + def test_timelapse_of_an_end_stamping_camera(self, tmp_path: Path) -> None: + """ + A camera that stamps the creation time at the end of the recording + stamps a timelapse as long after its start as it took to record + """ + probe_duration = float(_load_probe_output()["streams"][0]["duration"]) + capture_times = self._sample_timelapse( + tmp_path, + format_tags={"make": "RICOH", "model": "RICOH THETA X"}, + video_duration_ratio=10, + ) + start_time = PROBE_START_TIME - datetime.timedelta(seconds=10 * probe_duration) + assert capture_times == [ + start_time + datetime.timedelta(seconds=10 * idx) for idx in range(10) + ] + def test_timestamps_from_gps_clock(self, tmp_path: Path) -> None: """Frames at points with their own timestamp do not need the creation time.""" video_dir = tmp_path / "videos"