#needs: opencv-python and numpy
#run: "pip install -U opencv-python numpy"
import os
import shutil
import subprocess
import cv2
import numpy as np
INPUT_DIR = "input"
OUTPUT_DIR = "output"
VIDEO_EXTS = (".mp4", ".avi", ".mov", ".mkv", ".webm", ".flv", ".wmv", ".m4v")
# "dif" or "out"
mode = "dif"
print(f"mode: {mode}")
def find_ffmpeg():
  """Use ffmpeg from PATH, or the one bundled with imageio-ffmpeg."""
  path = shutil.which("ffmpeg")
  if path:
    return path
  try:
    import imageio_ffmpeg
    return imageio_ffmpeg.get_ffmpeg_exe()
  except ImportError:
    return None
def get_last_frame(in_path):
  """Decode through the video once and return its final frame (as int16)."""
  cap = cv2.VideoCapture(in_path)
  last = None
  while True:
    ok, frame = cap.read()
    if not ok:
      break
    last = frame
  cap.release()
  return None if last is None else last.astype(np.int16)
def process_video(in_path, silent_path):
  """Write the frame-difference video (no audio) to silent_path."""
  # Frame 1 gets compared against the last frame, so find that first.
  prev = get_last_frame(in_path)
  cap = cv2.VideoCapture(in_path)
  if not cap.isOpened():
    print(f"  Could not open {in_path}")
    return False
  fps = cap.get(cv2.CAP_PROP_FPS) or 21
  width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
  height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
  total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
  fourcc = cv2.VideoWriter_fourcc(*"mp4v")
  writer = cv2.VideoWriter(silent_path, fourcc, fps, (width, height))
  n = 0
  while True:
    ok, frame = cap.read()
    if not ok:
      break
    cur = frame.astype(np.int16)  # int16 so negative differences don't wrap
    if prev is None:
      diff = np.zeros_like(cur)  # only if the video had no readable frames
    else:
      diff = (cur - prev)  # change per pixel, per channel: -255..255
    if mode == "dif":
      duft = (diff + 0xFF) / 2
    if mode == "out":
      duft = abs(diff)
    out = duft.astype(np.uint8)
    writer.write(out)
    prev = cur
    n += 1
    if total > 0 and n % 100 == 0:
      print(f"  {n}/{total} frames")
  cap.release()
  writer.release()
  return True
def add_audio(ffmpeg, silent_path, original_path, out_path):
  """Combine the processed video with the original's audio (if it has any)."""
  cmd = [
    ffmpeg, "-y", "-loglevel", "error",
    "-i", silent_path,
    "-i", original_path,
    "-map", "0:v:0",
    "-map", "1:a:0?",  # the '?' means: skip if there is no audio track
    "-c:v", "copy",
    "-c:a", "aac",
    "-shortest",
    out_path,
  ]
  result = subprocess.run(cmd, capture_output=True, text=True)
  if result.returncode != 0:
    print(f"  ffmpeg failed: {result.stderr.strip()}")
    return False
  return True
def main():
  os.makedirs(INPUT_DIR, exist_ok=True)
  os.makedirs(OUTPUT_DIR, exist_ok=True)
  ffmpeg = find_ffmpeg()
  if ffmpeg is None:
    print("ffmpeg not found. Install it, or run: pip install imageio-ffmpeg")
    return
  files = [f for f in sorted(os.listdir(INPUT_DIR)) if f.lower().endswith(VIDEO_EXTS)]
  if not files:
    print(f"No video files found in '{INPUT_DIR}'.")
    return
  for name in files:
    stem = os.path.splitext(name)[0]
    in_path = os.path.join(INPUT_DIR, name)
    out_path = os.path.join(OUTPUT_DIR, stem + ".mp4")
    silent_path = os.path.join(OUTPUT_DIR, stem + "._silent_tmp.mp4")
    print(f"Processing {name} -> {out_path}")
    if not process_video(in_path, silent_path):
      continue
    if add_audio(ffmpeg, silent_path, in_path, out_path):
      os.remove(silent_path)
    else:
      # keep the silent video so the work isn't lost
      os.replace(silent_path, out_path)
      print("  Saved without audio.")
  print("Done.")
if __name__ == "__main__":
  main()