"""Q-2: Step through a video one frame at a time -- Data-Driven Athletics tutorial.

Web page: https://apopt.com/course/tutorials/q02-frame-step/
Data:     https://apopt.com/data/tutorials/q02-frame-step/ (keep raw/ next to this file)
"""

# %% [markdown]
# ### A video is a stack of pictures and a clock
#
# To time a jump from video you step through it one frame at a time and note the frame numbers
# where something happens. The frame number becomes a time only when you divide it by a frame
# rate, and a phone clip carries two of them: the rate the camera **recorded** at and the rate
# the file **stores** (Section 1.3.2, and Chapter 8). The clip here is the course's example jump,
# named `jump2_120fps.mp4` because it was filmed in slow motion at 120 frames per second.
#
# The first two cells run on your own computer or in Colab (they need OpenCV), because they read
# the video. They write a table with one row per frame and no pictures in it; from the third cell
# on, everything runs in this page from that table.

# %%
# Read the clip's header
import cv2

cap = cv2.VideoCapture("local/jump2_120fps.mp4")
fps_file = cap.get(cv2.CAP_PROP_FPS)
n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
w, h = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(f"{n} frames, header says {fps_file:.2f} fps, {w} x {h} pixels")
print(f"playback length {n / fps_file:.2f} s; at the 120 fps capture rate {n / 120:.2f} s")
cap.release()

# %% [markdown]
# The header says 30, not 120. The phone stored four times fewer frames per second than it
# recorded, so the clip plays four times slower than life. Played back it lasts 6.33 s; the real
# jump took 1.58 s.
#
# ### Step through every frame and write a table
#
# The loop reads one frame at a time. For each it writes the frame number, its time on both
# clocks, its mean brightness, and how much it differs from the frame before (the mean absolute
# difference of the gray values, 0 to 255). A difference near zero means the frame repeats the
# one before it. The cell also saves frames 78 to 84 as pictures under `local/` so you can look at
# them one by one on your computer; they are never published.

# %%
# One row per frame
import os
import numpy as np
import pandas as pd

os.makedirs("clean", exist_ok=True)
os.makedirs("local/frames", exist_ok=True)
cap = cv2.VideoCapture("local/jump2_120fps.mp4")
rows, prev, i = [], None, 0
while True:
    ok, frame = cap.read()
    if not ok:
        break
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).astype(float)
    diff = np.nan if prev is None else np.abs(gray - prev).mean()
    rows.append([i, i / fps_file, i / 120, gray.mean(), diff])
    if 78 <= i <= 84:
        cv2.imwrite(f"local/frames/frame_{i:03d}.jpg", frame)   # for your eyes only
    prev, i = gray, i + 1
cap.release()
table = pd.DataFrame(rows, columns=["frame", "t_file_s", "t_capture_s", "mean_gray", "diff_prev"])
table.round({"t_file_s": 6, "t_capture_s": 6, "mean_gray": 2, "diff_prev": 3}).to_csv("clean/frame_table.csv", index=False)
print(f"{len(table)} rows written to clean/frame_table.csv")

# %% [markdown]
# ### Step through the table
#
# From here on the cells run in this page. Print the rows around frame 80, where the book's hand
# count found the feet leaving the ground (Section 1.3, Example "A hand count on the course's
# example clip").

# %%
# Seven frames, two clocks
import pandas as pd

table = pd.read_csv("clean/frame_table.csv")
print(table[(table["frame"] >= 78) & (table["frame"] <= 84)].to_string(index=False))
step_ms = 1000 * (table["t_capture_s"].iloc[1] - table["t_capture_s"].iloc[0])
print(f"one frame = {step_ms:.1f} ms of real time; frames 80 to 124 = {(124 - 80) * step_ms / 1000:.3f} s")

# %% [markdown]
# One frame is 8.3 ms of real time, so the 44 frames from takeoff at frame 80 to landing at frame
# 124 are 0.367 s, the flight time the jump app also reports. Divided by the header's 30 the same
# 44 frames would be 1.467 s, four times too long.
#
# Look at the `diff_prev` column: frame 79 differs from frame 78 by almost nothing. Plot the
# difference for the whole clip to see whether that is chance.

# %%
# How much each frame changes
import matplotlib.pyplot as plt

repeat = table["diff_prev"] < 0.5
print(f"{int(repeat.sum())} repeated frames, at frames {table.loc[repeat, 'frame'].tolist()[:6]} ...")
print("gaps between repeats:", sorted(set(table.loc[repeat, "frame"].diff().dropna().astype(int))))
fig, ax = plt.subplots(figsize=(8, 3.4))
ax.plot(table["frame"], table["diff_prev"], "-", color="0.5", lw=1, label="every frame")
ax.plot(table.loc[repeat, "frame"], table.loc[repeat, "diff_prev"], "kx", ms=6, label="repeat (< 0.5)")
ax.set(xlabel="frame number", ylabel="difference from previous frame (gray levels)")
ax.legend()
plt.tight_layout()

# %% [markdown]
# Thirty-two frames, exactly every sixth one, repeat the frame before. The camera did not do
# that by chance: the file was made from the recording in a way that duplicated frames. It
# matters for timing. If the camera recorded 120 distinct frames a second, then six file frames
# hold only five distinct moments, and counting file frames at 8.3 ms each can overstate a
# duration by up to a fifth (Chapter 8 returns to this). The difference also traces the jump: it
# peaks near frame 76, the drive up, and near frame 134, the landing, and sags in between, near
# the top of the flight where the body moves slowest. The jump is visible in the table without
# looking at a single picture.
#
# **For the athlete:** "I timed your jump frame by frame from the slow-motion clip; for the next
# test, film at a normal-speed setting of 60 frames per second or more so each frame is one
# moment and the clock is the one the camera used."
