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: 5 additions & 1 deletion docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@

### 2.1 (In Development)

* No changes yet.
* [feature] New `time-code-start` config option and `--time-code-start` flag show the date and time of recording in the timecode overlay (`-tc`) [#285](https://github.com/Breakthrough/DVR-Scan/issues/285)
* `filename` reads the start time of each input from its file name (e.g. `20261116233730.avi`), `modified` uses the file modified time minus the duration, or give the start time of the first input as `YYYY-MM-DD HH:MM:SS` (which shifts dated file names to correct clock or time zone errors, or continues sequentially for undated files)
* In the app, set it with Timecode Start in the output options
* [bugfix] A start time at or after the end of the input, or an end time that is not after the start time, now gives an error. Before, the scan read 0 frames and found no events with no warning [#285](https://github.com/Breakthrough/DVR-Scan/issues/285)
* [bugfix] The Date column of the app input list now shows the file modified time instead of the creation time. On Windows, a copy (e.g. from an SD card) sets the creation time to the time of the copy [#285](https://github.com/Breakthrough/DVR-Scan/issues/285)

### 2.0 (2026-11-08)

Expand Down
23 changes: 23 additions & 0 deletions docs/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,10 @@ All time values can be given as a timecode (`HH:MM:SS` or `HH:MM:SS.nnn`), in se
* <b><pre>-tc, --time-code</pre></b> Draw time code of each frame on the top left corner.
<br/>Text properties (e.g. color, font size, margin) can be set with a [config file](#overlays_1).

* <b><pre>--time-code-start</pre></b> Show the date and time of recording in the time code (`-tc`) instead of the position in the video.
<br/>`filename`: read the start time of each input from its file name (e.g. `20261116233730.avi` or `VID_20261116_233730.mp4`). `modified`: use the file modified time minus the duration of the video. Or give the start time of the first input, e.g. `--time-code-start "2026-11-16 23:37:30"` (uses file name time differences for later inputs when present, otherwise assumes continuous recording).
<br/>See the [`time-code-start`](#text-overlays) config option for details.

* <b><pre>-fm, --frame-metrics</pre></b> Draw frame metrics, including motion score, on the top right corner.
<br/>Text properties (e.g. color, font size, margin) can be set with a [config file](#config-file).

Expand Down Expand Up @@ -733,6 +737,25 @@ Color values can be specified as either `(R,G,B)` or in hex as `0xFFFFFF`. Time
```
</span>

* <b><pre>time-code-start</pre></b>
Start time of the timecode overlay. If set, the timecode shows the date and time of recording instead of the position in the video. The time of each frame is the start time of its input video plus the position of the frame in that video. Times are local times, as the camera wrote them.
* `none`: show the position in the video.
* `filename`: read the start time of each input from its file name. The name must contain the date and time as `YYYYMMDDhhmmss`, with optional separators between the parts (e.g. `20261116233730.avi`, `VID_20261116_233730.mp4`, `2026-11-16_23-37-30.mp4`). If a file name has no date and time, the timecode shows the position in the video for that input.
* `modified`: use the file modified time minus the duration of the video. Many cameras set the modified time when a clip ends; cameras without a clock write a fixed date. A copy of the file usually keeps the modified time.
* A date and time as `YYYY-MM-DD HH:MM:SS`: the start time of the first input. If all input file names contain a date and time, later inputs are placed using the differences between their file name times. This corrects camera clock and time zone errors and allows gaps between clips within one power cycle (after a power loss, a camera clock may reset to a factory default time). If any file name has no date and time, later inputs continue from the first input as if the recording was continuous.

The time can be wrong if the frame rate in the file is not the rate at which the camera recorded. If you save a fixed date and time in a preset or in the Default config file, it applies to all later scans until changed.
<span class="dvr-scan-default">
```
time-code-start = none
```
</span>
<span class="dvr-scan-example">
```
time-code-start = filename
```
</span>

* <b><pre>frame-metrics</pre></b>
Enable frame metrics overlay: (`yes` or `no`). Draws frame metrics, including motion score, on top right of each frame.
<span class="dvr-scan-example">
Expand Down
12 changes: 12 additions & 0 deletions dvr-scan.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,18 @@ startup-mode = WIZARD
# Enable/disable timecode overlay in top-left of video frame.
#time-code = yes

# Start time of the timecode overlay. Set it to show the date and time of
# recording instead of the position in the video:
# - filename: read the start time of each input from the file name
# (e.g. 20261116233730.avi or VID_20261116_233730.mp4).
# - modified: the file modified time minus the duration of the video. Many
# cameras set this when a clip ends; cameras without a clock write a fixed date.
# - YYYY-MM-DD HH:MM:SS: the start time of the first input. If all input file
# names contain a date and time, later inputs are placed using the differences
# between their file name times (one power cycle); otherwise later inputs
# continue from the first input as if the recording was continuous.
#time-code-start = none

# Enable/disable frame metrics overlay in top right of video frame.
#frame-metrics = yes

Expand Down
88 changes: 88 additions & 0 deletions dvr_scan/app/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
PADDING,
SETTING_INPUT_WIDTH,
MenuBar,
Tooltip,
add_startup_mode_menu,
fill_help_menu,
fit_window_to_screen,
Expand Down Expand Up @@ -68,6 +69,7 @@
from dvr_scan.scanner import OutputMode, Point
from dvr_scan.shared import ScanSettings, finalize_output_names, resolve_output_mode
from dvr_scan.subtractor import SubtractorCNT, SubtractorCudaMOG2
from dvr_scan.wallclock import TIME_CODE_START_CHOICES, normalize_time_code_start

WINDOW_TITLE = "DVR-Scan"
LONG_SETTING_INPUT_WIDTH = 72
Expand Down Expand Up @@ -215,6 +217,13 @@ def __init__(self, root: tk.Widget):

self._end_time_label = tk.Label(root, text="End Time")
self._end_time = TimecodeEntry(root, "00:00:00.000")
# Times are positions in the video, not times of day (#285).
start_time_tip = "Position in the video to start the scan."
end_time_tip = "Position in the video to end the scan (0 = end of video)."
Tooltip(self._start_time_label, start_time_tip)
Tooltip(self._start_time.widget, start_time_tip)
Tooltip(self._end_time_label, end_time_tip)
Tooltip(self._end_time.widget, end_time_tip)

ttk.Checkbutton(
root,
Expand Down Expand Up @@ -1136,6 +1145,28 @@ def clear_output_directory():
row=1, column=1, sticky=tk.W, padx=PADDING, pady=(PADDING, 0)
)

# Start time of the timecode: a choice, or a date and time that the user types.
time_code_start_tip = (
"Show recording date and time in the timecode: choose none, filename, or modified,"
" or type YYYY-MM-DD HH:MM:SS."
)
time_code_start_label = tk.Label(self._opencv_options, text="Timecode Start")
time_code_start_label.grid(
row=1, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0)
)
self._last_valid_time_code_start = str(CONFIG_MAP["time-code-start"])
self._time_code_start = tk.StringVar(value=self._last_valid_time_code_start)
self._time_code_start_combo = ttk.Combobox(
self._opencv_options,
textvariable=self._time_code_start,
values=list(TIME_CODE_START_CHOICES),
)
self._time_code_start_combo.grid(
row=1, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0)
)
Tooltip(time_code_start_label, time_code_start_tip)
Tooltip(self._time_code_start_combo, time_code_start_tip)

tk.Label(self._opencv_options, text="Text Color").grid(
row=2, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0)
)
Expand Down Expand Up @@ -1319,6 +1350,7 @@ def _on_text_overlay(self):
self._text_margin["state"] = state
self._text_bg_color["state"] = state
self._text_font_color["state"] = state
self._time_code_start_combo["state"] = tk.NORMAL if self._timecode.get() else tk.DISABLED

def _on_bounding_box(self):
state = tk.NORMAL if self._bounding_box.get() else tk.DISABLED
Expand Down Expand Up @@ -1375,6 +1407,9 @@ def load(self, settings: ScanSettings):
self._encode_args.set(settings.get("encode-args"))
# Text Overlays
self._timecode.set(settings.get("time-code"))
time_code_start = str(settings.get("time-code-start"))
self._time_code_start.set(time_code_start)
self._last_valid_time_code_start = time_code_start
self._frame_metrics.set(settings.get("frame-metrics"))
self._text_font_color.set(settings.get("text-font-color"))
self._text_bg_color.set(settings.get("text-bg-color"))
Expand All @@ -1390,6 +1425,23 @@ def load(self, settings: ScanSettings):
self._bounding_box_thickness.set(settings.get("bounding-box-thickness"))
self._on_mode_combo_selected()

def validate_time_code_start(self) -> str:
"""Validate and normalize the Timecode Start field when active.

Raises:
ValueError: Timecode overlay is enabled and the entered value is not valid.
"""
if (
self._output_mode not in (OutputMode.OPENCV, OutputMode.ENCODE)
or not self._timecode.get()
):
return self._last_valid_time_code_start
raw = self._time_code_start.get().strip() or "none"
normalized = normalize_time_code_start(raw)
self._last_valid_time_code_start = normalized
self._time_code_start.set(normalized)
return normalized

def save(self, settings: ScanSettings) -> ScanSettings:
settings.set("output-mode", self._output_mode)
if self._output_dir:
Expand All @@ -1404,6 +1456,19 @@ def save(self, settings: ScanSettings) -> ScanSettings:
settings.set("encode-args", self._encode_args.get())
# Text Overlays
settings.set("time-code", self._timecode.get())
raw_start = self._time_code_start.get().strip() or "none"
try:
normalized_start = normalize_time_code_start(raw_start)
self._last_valid_time_code_start = normalized_start
settings.set("time-code-start", normalized_start)
except ValueError:
# Keep the last valid value when the field is disabled so saved configs
# cannot be corrupted; keep the raw value when active so UI state diffs
# detect unsaved edits without throwing.
settings.set(
"time-code-start",
raw_start if self._timecode.get() else self._last_valid_time_code_start,
)
settings.set("frame-metrics", self._frame_metrics.get())
settings.set("text-font-color", self._text_font_color.get())
settings.set("text-bg-color", self._text_bg_color.get())
Expand Down Expand Up @@ -1776,6 +1841,8 @@ def _open_wizard(self, initial: bool = False):
get_scan_overrides=self._input_area.scan_overrides,
)
if not initial:
if not self._validate_ui_settings():
return
self._wizard.sync_from_settings(
self._get_config_settings(), active_preset=self._active_preset
)
Expand Down Expand Up @@ -1848,11 +1915,28 @@ def _destroy(self):
self._root.after(0, lambda: self._root.destroy())
self._root.withdraw()

def _validate_ui_settings(self) -> bool:
"""Validate editable UI fields before scanning, saving configs/presets, or switching
to Scan Wizard. Shows an error dialog and returns False on failure."""
try:
self._output_area.validate_time_code_start()
except ValueError as ex:
tkinter.messagebox.showerror(
title="Invalid Setting",
message=str(ex),
parent=self._root,
)
return False
return True

def _start_scan(self):
# It should not be possible to start two scans in parallel with the current UI.
# Once we start a scan, the scan window should grab input focus until it is closed.
assert self._scan_window is None

if not self._validate_ui_settings():
return

# TODO: Instead of just returning None below if the settings are invalid or we can't start
# the scan (e.g. no input videos selected), we should throw an exception and catch it here.
# We should then display a messagebox to the user indicating why the scan couldn't start.
Expand Down Expand Up @@ -1942,6 +2026,8 @@ def _initialize(self, settings: ScanSettings):
self._scan_area.load(settings)

def _on_save_config(self):
if not self._validate_ui_settings():
return
save_path = tkinter.filedialog.asksaveasfilename(
title="Save Config File...",
filetypes=[("Config File", "*.cfg")],
Expand Down Expand Up @@ -2009,6 +2095,8 @@ def _on_preset_selected(self, preset: presets.Preset):
self._on_preset_applied(preset, config)

def _on_save_preset(self):
if not self._validate_ui_settings():
return
name = tkinter.simpledialog.askstring(
title="Save Preset",
prompt="Preset name:",
Expand Down
40 changes: 40 additions & 0 deletions dvr_scan/app/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,46 @@ def hide_modal(window: tk.Toplevel, focus: tk.Misc):
focus.focus()


class Tooltip:
"""A minimal hover tooltip, e.g. to label icon-only buttons."""

def __init__(self, widget: tk.Widget, text: str):
self._widget = widget
self._text = text
self._tip: ty.Optional[tk.Toplevel] = None
widget.bind("<Enter>", self._show, add="+")
widget.bind("<Leave>", self._hide, add="+")
widget.bind("<ButtonPress>", self._hide, add="+")
# Tear down a visible tip if the widget is hidden or destroyed while hovered.
widget.bind("<Unmap>", self._hide, add="+")
widget.bind("<Destroy>", self._hide, add="+")

def _show(self, _event=None):
if self._tip is not None or not self._widget.winfo_exists():
return
x = self._widget.winfo_rootx() + self._widget.winfo_width() // 2
y = self._widget.winfo_rooty() + self._widget.winfo_height() + 2
self._tip = tk.Toplevel(self._widget)
self._tip.wm_overrideredirect(True)
self._tip.wm_geometry(f"+{x}+{y}")
tk.Label(
self._tip,
text=self._text,
justify=tk.LEFT,
wraplength=320,
background="#ffffe0",
relief=tk.SOLID,
borderwidth=1,
padx=4,
pady=1,
).pack()

def _hide(self, _event=None):
if self._tip is not None:
self._tip.destroy()
self._tip = None


class MenuBar:
"""A custom menubar built from `tk.Menubutton` headings so the top-level menus get a
real hover highlight. The native Windows menubar (`toplevel["menu"] = ...`) exposes no
Expand Down
17 changes: 9 additions & 8 deletions dvr_scan/app/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,28 +51,29 @@ def parse_resolution(text: str) -> ty.Optional[ty.Tuple[int, int]]:


def probe_video(path: str) -> ty.Optional[VideoInfo]:
"""Open `path` and extract display metadata (duration, framerate, resolution, creation
"""Open `path` and extract display metadata (duration, framerate, resolution, modified
date), returning a `VideoInfo` or None if the video could not be opened. Errors are
logged by `open_video`; callers decide how to surface a failure to the user."""
try:
video = open_video(path, backend="opencv") # logs errors on failure
except VideoOpenFailure:
return None
try:
# On Windows, ctime is creation time. On other systems, it may be the last
# metadata change time.
create_time = datetime.fromtimestamp(Path(path).stat().st_ctime)
create_time_str = create_time.strftime("%Y-%m-%d %H:%M:%S")
except OSError as ex:
# Use the modified time, not ctime. On Windows, ctime is the creation time of the
# file, so a copy (e.g. from an SD card) sets it to the time of the copy. A copy
# keeps the modified time, which many cameras set when a clip ends (#285).
modified_time = datetime.fromtimestamp(Path(path).stat().st_mtime)
modified_time_str = modified_time.strftime("%Y-%m-%d %H:%M:%S")
except (OSError, OverflowError, ValueError) as ex:
logger.debug(f"Failed to stat {path}: {ex}")
create_time_str = "N/A"
modified_time_str = "N/A"
return VideoInfo(
path=str(Path(video.path).absolute()),
name=Path(video.path).name,
duration=video.duration.get_timecode(),
framerate=f"{float(video.frame_rate):g}",
resolution=f"{video.frame_size[0]} x {video.frame_size[1]}",
date=create_time_str,
date=modified_time_str,
)


Expand Down
Loading
Loading