Skip to content

Commit

Permalink
Add --title-screen-map argument to generate a map of the event locati…
Browse files Browse the repository at this point in the history
…on first in the movie
  • Loading branch information
SimonKagstrom committed Apr 24, 2021
1 parent 94afb17 commit 3b0c6a7
Showing 1 changed file with 112 additions and 0 deletions.
112 changes: 112 additions & 0 deletions tesla_dashcam/tesla_dashcam.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import os
import sys
import json
import shutil
from datetime import datetime, timedelta, timezone
from glob import glob, iglob
from pathlib import Path
Expand All @@ -23,6 +24,13 @@
from psutil import disk_partitions
from tzlocal import get_localzone

has_staticmap = False
try:
import staticmap
has_staticmap = True
except ImportError:
pass

_LOGGER = logging.getLogger(__name__)

# TODO: Move everything into classes and separate files. For example,
Expand Down Expand Up @@ -1947,12 +1955,38 @@ def create_intermediate_movie(
return True


def create_title_screen(event_metadata):
""" Create a map centered around the event """
if has_staticmap == False:
return None

if event_metadata == None:
return None

try:
lon = float(event_metadata["longitude"])
lat = float(event_metadata["latitude"])
except:
return None

m = staticmap.StaticMap(1920, 960)
marker_outline = staticmap.CircleMarker((lon, lat), 'white', 18)
marker = staticmap.CircleMarker((lon, lat), '#0036FF', 12)

m.add_marker(marker_outline)
m.add_marker(marker)

image = m.render(zoom=13)

return image

def create_movie(
movie,
event_info,
movie_filename,
video_settings,
chapter_offset,
title_image,
):
""" Concatenate provided movie files into 1."""
# Just return if there are no clips.
Expand Down Expand Up @@ -2050,6 +2084,12 @@ def create_movie(
with os.fdopen(ffmpeg_meta_filehandle, "w") as fp:
fp.write(meta_content)

title_image_filename = None
if title_image:
title_image_fh, title_image_filename = mkstemp(suffix=".png", text=False)

title_image.save(title_image_filename)

ffmpeg_params = [
"-f",
"concat",
Expand Down Expand Up @@ -2131,6 +2171,56 @@ def create_movie(
moviefile_timestamp = mktime(moviefile_timestamp.timetuple())
os.utime(movie_filename, (moviefile_timestamp, moviefile_timestamp))

if title_image_filename and movie_filename:
movie_filename_tmp = movie_filename + '.tmp'
shutil.move(movie_filename, movie_filename_tmp)
ffmpeg_params = [
"-y",
"-loop",
"1",
"-framerate",
"24",
"-t",
"3",
"-i",
title_image_filename,
"-i",
movie_filename_tmp,
"-filter_complex",
"[0:0] [1:0] concat=n=2:v=1:a=0",
movie_filename,
]
ffmpeg_command = (
[video_settings["ffmpeg_exec"]]
+ ["-loglevel", "error"]
+ ffmpeg_params
)
if movie.duration:
movie.duration = movie.duration + 3

try:
run(ffmpeg_command, capture_output=True, check=True)
except CalledProcessError as exc:
print(
"\t\tError trying to create movie {base_name}. RC: {rc}\n"
"\t\tCommand: {command}\n"
"\t\tError: {stderr}\n\n".format(
base_name=movie_filename,
rc=exc.returncode,
command=exc.cmd,
stderr=exc.stderr,
)
)
movie_filename = None
duration = 0

try:
os.remove(movie_filename_tmp)
except:
_LOGGER.debug(f"Failed to remove {movie_filename_tmp}")
pass


# Remove temp join file.
# noinspection PyBroadException,PyPep8
try:
Expand All @@ -2147,6 +2237,13 @@ def create_movie(
_LOGGER.debug(f"{get_current_timestamp()}Failed to remove {ffmpeg_meta_filename}")
pass

try:
if title_image_filename:
os.remove(title_image_filename)
except:
_LOGGER.debug(f"Failed to remove {title_image_filename}")
pass

if movie.filename is None:
return False

Expand Down Expand Up @@ -2408,11 +2505,17 @@ def process_folders(source_folders, video_settings, delete_source):
# together now.
print(f"{get_current_timestamp()}\t\tCreating movie {event_movie_filename}, please be patient.")


title_image = None
if video_settings["video_layout"].title_screen_map:
title_image = create_title_screen(event_info.metadata)

if create_movie(event_info,
event_info,
event_movie_filename,
video_settings,
0,
title_image,
):
if event_info.filename is not None:
if movies.get(event_info.template(merge_group_template, timestamp_format, video_settings)) is None:
Expand Down Expand Up @@ -2482,6 +2585,7 @@ def process_folders(source_folders, video_settings, delete_source):
movie_filename,
video_settings,
video_settings["chapter_offset"],
None,
):

if movies.get(movie).filename is not None:
Expand Down Expand Up @@ -2866,6 +2970,13 @@ def main() -> int:
help="Background color for video. Can be a color string or RGB value. Also see --fontcolor.",
)

layout_group.add_argument(
"--title-screen-map",
dest="title_screen_map",
action="store_true",
help="Show a map of the event location for the first 3 seconds of the movie. Requires the staticmap package",
)

camera_group = parser.add_argument_group(
title="Camera Exclusion", description="Exclude one or more cameras:"
)
Expand Down Expand Up @@ -3410,6 +3521,7 @@ def main() -> int:
)

layout_settings.swap_front_rear = args.swap_frontrear
layout_settings.title_screen_map = args.title_screen_map

layout_settings.font.font = args.font
layout_settings.font.color = args.fontcolor
Expand Down

0 comments on commit 3b0c6a7

Please sign in to comment.