Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/command_reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,11 @@ Gotchas:
- An import path that is gone, such as a file deleted or moved since `process`, is skipped with an error, and
the files of the others are uploaded. The upload summary counts the import paths skipped. The command stops
(exit code 3) only when none of them is found.
- A video whose upload would be larger than 32 GiB (`MAPILLARY_TOOLS_MAX_VIDEO_UPLOAD_SIZE`) is uploaded in pieces of
about equal length, one sequence for each, cut at its keyframes from its first GPS point to its last, without
re-encoding it; so is a part of its track between gaps (see [GPX and NMEA tracks](#gpx-and-nmea-tracks)). Mapillary
cannot process the upload of a video of about 100 GB. A video that cannot be cut, or whose keyframes are so far apart
that its pieces would upload a tenth more than it, is uploaded whole, with a warning.
- Uploading a folder of zip files also needs a description file: pass the one of the zipped images with
`--desc_path`.
- `--delete_after_upload` deletes each image, video and zip file once Mapillary has confirmed that its upload
Expand Down Expand Up @@ -654,6 +659,7 @@ in the user data folder (or `MAPILLARY_TOOLS_EXIFTOOL_INSTALL_DIR`) and prints t
| `MAPILLARY_TOOLS_MAX_GPX_GAP_SECONDS` | 3600 | The longest gap in a GPX or NMEA track that files can be placed in, and how far from the rest of a track ExifTool points can be. |
| `MAPILLARY_TOOLS_MAX_GPX_SEGMENT_GAP_SECONDS` | 5 | The longest time between two segments of a GPX track inside a video that `process` keeps no gap for. |
| `MAPILLARY_UPLOAD_HISTORY_PATH` | in the user data folder | Where the upload history is kept. |
| `MAPILLARY_TOOLS_MAX_VIDEO_UPLOAD_SIZE` | `32G` | The largest upload of a video as one sequence: a larger one is uploaded in pieces (see [`upload`](#upload)). `INF` for no limit. |
| `MAPILLARY_TOOLS_MAX_SEQUENCE_LENGTH` | 1000 | The most images in a sequence. |
| `MAPILLARY_TOOLS_MAX_CAPTURE_SPEED_KMH` | 400 | The fastest average speed that passes the speed check. |
| `MAPILLARY_TOOLS_IMAGE_DESCRIPTION_FILENAME` | `mapillary_image_description.json` | The default name of the description file. |
Expand Down
8 changes: 8 additions & 0 deletions mapillary_tools/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,14 @@ def _parse_scaled_integers(
# but it affects the responsiveness of the upload progress bar
UPLOAD_CHUNK_SIZE_MB: float = float(os.getenv(_ENV_PREFIX + "UPLOAD_CHUNK_SIZE_MB", 2))
MAX_UPLOAD_RETRIES: int = int(os.getenv(_ENV_PREFIX + "MAX_UPLOAD_RETRIES", 200))
# The largest upload of a video as one sequence. A larger video, or part of
# its track between gaps, is uploaded in pieces of about equal length, each a
# sequence of its own (see uploader.VideoUploader). Mapillary keeps a handle
# of about 210 bytes for each 20 MB uploaded with the sequence, and cannot
# keep that of an upload of about 100 GB with the positions of its frames
MAX_VIDEO_UPLOAD_SIZE: int | None = _parse_filesize(
os.getenv(_ENV_PREFIX + "MAX_VIDEO_UPLOAD_SIZE", "32G")
)
MAPILLARY__ENABLE_UPLOAD_HISTORY_FOR_DRY_RUN: bool = _yes_or_no(
os.getenv("MAPILLARY__ENABLE_UPLOAD_HISTORY_FOR_DRY_RUN", "NO")
)
Expand Down
276 changes: 223 additions & 53 deletions mapillary_tools/uploader.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
else:
from typing_extensions import Required

import humanize
import requests

from . import (
Expand Down Expand Up @@ -287,7 +288,7 @@ def upload_videos(
)
if len(part) >= 2
]
if 2 <= len(parts):
if 2 <= len(parts) or _larger_than_an_upload(video_metadata):
yield from cls._upload_video_in_pieces(
mly_uploader, video_metadata, parts, progress
)
Expand Down Expand Up @@ -327,11 +328,13 @@ def _upload_video_in_pieces(
progress: SequenceProgress,
) -> T.Generator[tuple[types.VideoMetadata, UploadResult], None, None]:
"""
Upload a video in pieces, one for each part of its track between gaps
(see types.VideoMetadata.track_gaps), each a sequence of its own: the
video from the sync sample before the first point of the part to the
Upload a video in pieces, each a sequence of its own: one for each
part of its track between gaps (see types.VideoMetadata.track_gaps),
and pieces of about equal length of a part, or of a video without
gaps, that would upload more than constants.MAX_VIDEO_UPLOAD_SIZE. A
piece is the video from the sync sample before its first point to the
one after its last (see simple_mp4_builder.transform_mp4_cut()), with
the CAMM track of the part. Each piece reads its own samples of the
the CAMM track of its points. Each piece reads its own samples of the
video only, and the video in the gaps is not uploaded.

Upload the video whole, as one sequence, if it cannot be cut, or if
Expand All @@ -342,36 +345,38 @@ def _upload_video_in_pieces(
pieces (see UploadResult).
"""
name = video_metadata.filename.name
keys = [_video_piece_key(part) for part in parts]
# Yielded once the video is closed, so that it can be deleted once it
# is uploaded (see upload.upload()), which no file open on Windows can
last_result: UploadResult
with video_metadata.filename.open("rb") as src_fp:
try:
camm_info = cls.prepare_camm_info(video_metadata)
try:
cuts = cls._cut_pieces(src_fp, name, camm_info, parts)
if cuts is None:
pieces = cls._cut_pieces(
src_fp, name, camm_info, video_metadata.points, parts
)
if pieces is None:
whole = simple_mp4_builder.transform_mp4(
src_fp, camm_builder.camm_sample_generator2(camm_info)
)
except camm_builder.SampleDurationOverflowError as ex:
raise GPSPointsTooFarApartError(f"{name}: {ex}") from ex
if cuts is None:
if pieces is None:
last_result = UploadResult(
result=cls._upload_and_finish(mly_uploader, whole, progress)
)
except Exception as ex:
last_result = UploadResult(error=ex)
cuts = None
pieces = None

if cuts is not None:
if pieces is not None:
keys = [_video_piece_key(part) for part, _ in pieces]
LOG.info(
"%s: Uploading the video in %d pieces, one sequence for each part of its track between gaps",
"%s: Uploading the video in %d pieces, one sequence for each",
name,
len(cuts),
len(pieces),
)
for piece_idx, cut in enumerate(cuts):
for piece_idx, (_, cut) in enumerate(pieces):
piece_progress: SequenceProgress = {
**progress,
"sequence_md5sum": upload_key(
Expand All @@ -389,7 +394,7 @@ def _upload_video_in_pieces(
)
except Exception as ex:
last_result.error = ex
if piece_idx + 1 < len(cuts):
if piece_idx + 1 < len(pieces):
yield video_metadata, last_result

yield video_metadata, last_result
Expand All @@ -400,61 +405,154 @@ def _cut_pieces(
src_fp: T.BinaryIO,
name: str,
camm_info: camm_parser.CAMMInfo,
points: T.Sequence[geo.Point],
parts: T.Sequence[T.Sequence[geo.Point]],
) -> list[simple_mp4_builder.MP4Cut] | None:
) -> list[tuple[T.Sequence[geo.Point], simple_mp4_builder.MP4Cut]] | None:
"""
Cut the video into the pieces of its parts, with the measurements of
**camm_info** within each, or return None if it cannot be cut, or if
the pieces would upload more of it than all of it. The video is then
uploaded whole, as it would be without gaps, also where cutting it
fails in a way that it should not
Cut the video into its pieces, each with its points and the
measurements of **camm_info** within them: one for each of its
**parts** between gaps, if there are 2 or more, and pieces of about
equal length of those, or of the whole track (**points**), that would
upload more than constants.MAX_VIDEO_UPLOAD_SIZE.

Return None to upload the video whole, as one sequence: if its upload
is no larger than that and it has fewer than 2 parts, or if its sync
samples are so far apart that the pieces between the gaps would
upload more of it than all of it; or if it cannot be cut at the gaps,
also where cutting it fails in a way that it should not, or not into
smaller pieces
"""
cuts: list[simple_mp4_builder.MP4Cut] = []
max_size = constants.MAX_VIDEO_UPLOAD_SIZE
header: simple_mp4_builder.MP4Header

def cut(part: T.Sequence[geo.Point]) -> simple_mp4_builder.MP4Cut:
start, end = part[0].time, part[-1].time
part_camm_info = _camm_info_between(camm_info, start, end)

def sample_generator_factory(cut_start: float):
return camm_builder.camm_sample_generator2(
_shift_camm_info(part_camm_info, -cut_start)
)

return simple_mp4_builder.transform_mp4_cut(
src_fp, header, start, end, sample_generator_factory
)

pieces: list[tuple[T.Sequence[geo.Point], simple_mp4_builder.MP4Cut]]
pieces = []
try:
header = simple_mp4_builder.MP4Header.read(src_fp)
whole = simple_mp4_builder.transform_mp4_cut(src_fp, header, 0, math.inf)
for part in parts:
start, end = part[0].time, part[-1].time
part_camm_info = _camm_info_between(camm_info, start, end)

def sample_generator_factory(
cut_start: float, part_camm_info=part_camm_info
):
return camm_builder.camm_sample_generator2(
_shift_camm_info(part_camm_info, -cut_start)
)

cuts.append(
simple_mp4_builder.transform_mp4_cut(
src_fp, header, start, end, sample_generator_factory
)
)
if 2 <= len(parts):
pieces = [(part, cut(part)) for part in parts]
except camm_builder.SampleDurationOverflowError:
# The whole video has the points of the pieces
raise
except Exception as ex:
LOG.warning(
"%s: Uploading the video whole, as one sequence: it cannot be cut at the gaps of its track: %s",
name,
ex
if isinstance(ex, simple_mp4_builder.MP4CutError)
else f"{type(ex).__name__}: {ex}",
_cut_error(ex),
)
return None

# The pieces overlap where the sync samples of the video are further
# apart than the gaps are long
whole_duration = whole.end - whole.start
pieces_duration = sum(cut.end - cut.start for cut in cuts)
if whole_duration < pieces_duration:
LOG.warning(
"%s: Uploading the video whole, as one sequence: its sync samples are so far apart that its pieces between the gaps of its track would upload %.1f seconds of it, more than all of it (%.1f seconds)",
name,
pieces_duration,
whole_duration,
)
if pieces:
# The pieces overlap where the sync samples of the video are
# further apart than the gaps are long
whole_duration = whole.end - whole.start
pieces_duration = sum(c.end - c.start for _, c in pieces)
if whole_duration < pieces_duration:
LOG.warning(
"%s: Uploading the video whole, as one sequence: its sync samples are so far apart that its pieces between the gaps of its track would upload %.1f seconds of it, more than all of it (%.1f seconds)",
name,
pieces_duration,
whole_duration,
)
pieces = []

if max_size is None:
return pieces or None
if not pieces:
if _stream_size(whole.stream) <= max_size:
return None
track = sorted(points, key=lambda p: p.time)
if len(track) < 2:
return None
try:
pieces = [(track, cut(track))]
except camm_builder.SampleDurationOverflowError:
raise
except Exception as ex:
LOG.warning(
"%s: Uploading the video whole, as one sequence, although it is larger than %s: it cannot be cut: %s",
name,
humanize.naturalsize(max_size, binary=True),
_cut_error(ex),
)
return None

pieces = [
smaller
for part, part_cut in pieces
for smaller in cls._split_piece(name, cut, part, part_cut, max_size)
]
# The piece of the whole track, kept whole
if len(pieces) < 2:
return None
return cuts
return pieces

@classmethod
def _split_piece(
cls,
name: str,
cut: T.Callable[[T.Sequence[geo.Point]], simple_mp4_builder.MP4Cut],
part: T.Sequence[geo.Point],
part_cut: simple_mp4_builder.MP4Cut,
max_size: int,
) -> list[tuple[T.Sequence[geo.Point], simple_mp4_builder.MP4Cut]]:
"""
Split the piece of a part of the track that would upload more than
**max_size** into pieces of about equal length that would not, each
cut with **cut**. Keep a piece whole, with a warning, where it cannot
be split, such as a part of 3 points or fewer, or where its sync
samples are so far apart that its pieces would upload a tenth more
than it, or more. The video between the last point of a piece and the
first of the next one may be in neither
"""
size = _stream_size(part_cut.stream)
if size <= max_size:
return [(part, part_cut)]

smaller_parts = _split_part(part, math.ceil(size / max_size))
if 2 <= len(smaller_parts):
try:
smaller_cuts = [cut(p) for p in smaller_parts]
except camm_builder.SampleDurationOverflowError:
raise
except Exception as ex:
reason = f"it cannot be cut: {_cut_error(ex)}"
else:
smaller_size = sum(_stream_size(c.stream) for c in smaller_cuts)
if smaller_size <= size * 1.1:
return [
smaller
for p, c in zip(smaller_parts, smaller_cuts)
for smaller in cls._split_piece(name, cut, p, c, max_size)
]
reason = f"its sync samples are so far apart that its pieces would upload {humanize.naturalsize(smaller_size, binary=True)}"
else:
reason = "its points cannot be split into pieces of 2 points or more"

LOG.warning(
"%s: Uploading %s of the video, from %.1f to %.1f seconds, as one sequence, although it is larger than %s: %s",
name,
humanize.naturalsize(size, binary=True),
part[0].time,
part[-1].time,
humanize.naturalsize(max_size, binary=True),
reason,
)
return [(part, part_cut)]

@classmethod
@contextmanager
Expand Down Expand Up @@ -541,6 +639,78 @@ def prepare_camm_info(
return camm_info


def _larger_than_an_upload(video_metadata: types.VideoMetadata) -> bool:
"""
Whether the video file is larger than constants.MAX_VIDEO_UPLOAD_SIZE,
so that its upload may need to be in pieces: its upload leaves out some
of its tracks, such as audio, and may be smaller
"""
max_size = constants.MAX_VIDEO_UPLOAD_SIZE
if max_size is None:
return False
try:
size = (
utils.get_file_size(video_metadata.filename)
if video_metadata.filesize is None
else video_metadata.filesize
)
except OSError:
# Fails where the video is uploaded whole
return False
return max_size < size


def _split_part(part: T.Sequence[geo.Point], count: int) -> list[T.Sequence[geo.Point]]:
"""
Split a part of a track (in time order) at its points into up to
**count** parts of about equal duration, each of 2 points or more

>>> p = lambda t: geo.Point(time=t, lat=0, lon=0, alt=None, angle=None)
>>> [[q.time for q in s] for s in _split_part([p(t) for t in range(7)], 2)]
[[0, 1, 2], [3, 4, 5, 6]]
>>> [[q.time for q in s] for s in _split_part([p(t) for t in range(9)], 3)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> [[q.time for q in s] for s in _split_part([p(0), p(1), p(2), p(9), p(10)], 3)]
[[0, 1, 2], [9, 10]]
>>> [[q.time for q in s] for s in _split_part([p(0), p(1), p(10)], 2)]
[[0, 1, 10]]
"""
start, end = part[0].time, part[-1].time

def boundary(idx: int) -> float:
return start + (end - start) * idx / count

smaller_parts: list[list[geo.Point]] = [[]]
boundary_idx = 1
for point in part:
if (
boundary_idx < count
and boundary(boundary_idx) <= point.time
and 2 <= len(smaller_parts[-1])
):
smaller_parts.append([])
while boundary_idx < count and boundary(boundary_idx) <= point.time:
boundary_idx += 1
smaller_parts[-1].append(point)
if 2 <= len(smaller_parts) and len(smaller_parts[-1]) < 2:
smaller_parts[-2].extend(smaller_parts.pop())
return list(smaller_parts)


def _stream_size(stream: io.IOBase) -> int:
"""The size of a stream, which is left at its start"""
size = stream.seek(0, io.SEEK_END)
stream.seek(0, io.SEEK_SET)
return size


def _cut_error(ex: Exception) -> str:
"""Why a video cannot be cut, as a warning says it"""
if isinstance(ex, simple_mp4_builder.MP4CutError):
return str(ex)
return f"{type(ex).__name__}: {ex}"


def _video_piece_key(part: T.Sequence[geo.Point]) -> str:
"""
The key of the piece of a video for a part of its track: its span, in
Expand Down
Loading
Loading