Variable Frame-Rate Detection + Re-Sync Tool + Duplicate Frame Fix (Python) [UPDATED, AGAIN]

Thumbnail

UPDATE: here’s an actual explanation of VFR

…

What is VFR: VFR, or variable frame rate, is essentially when a video has different FPS values across the length of the video; so one section is 25fps, another is 28.56fps, another is 100fps. This causes “speed” issues in playback because each frame has a position in time where it is supposed to be. When a CFR video is converted to VFR, all of the frame data for the video is shifted a microscopic amount for each inserted frame. That leads to an imperceptible to the eye drift in the timing of the video. Funscripts are based on their own independent clock-time and are not locked to the video frames. This means that over time the scripts will desync from the video and drift.

…

Hey all, not sure I have the brain capacity to make a huge post explaining this problem super well. Hopefully if you run into this issue, or see someone else run into it you can refer them here.

Have you ever had a script that WAS synced perfectly to one version of a video, but when you download a different version from another streaming service it is suddenly completely desynced, and no amount of tweaking seems to resync the script? Or have you ever downloaded a video from a scripter who posted previews of a perfectly synced script, but when you went and found the video, your script doesn’t sync the way their script does?

This problem (what @roa has been calling the “exponential FPS desync bug”) is actually a problem with video encoding that @g90ak taught me about called VFR or variable frame rate.

Turns out that that poor pacing and jerkiness g90ak was talking about, when translated from a constant frame rate (CFR) script to a VFR playback is a nightmare of desyncing. Check out this desync from a recent post by @POVScripter. Post here: https://discuss.eroscripts.com/t/hot-redhead-likes-it-big-and-black-atkins-heaven-updated-link/327085

vs what it should look like:

OpenFunscripter_1J2Nh7kjqG

Basically, this incredible amount desync occurs because pornhub (and other sites) has shitty video-storage practices, and because of that, scripters who want to avoid this issue need to do a bit more work.

So … I wrote more shitty python code (you’re welcome) that allows you to detect & fix this VFR problem. So your file can go from the desync above, to this:


And yes, this is actually the resynced video file and not just a clip of the script being played over POVscripters original copy of the video.

UPDATE: Turns out some streaming services literally LIE when they write their fps metadata so the original, slightly lazy, version of this script doesn’t always work (fuck you pornhub.) The V1 version of this script will work 90% of the time, but sometimes will not flag a VFR video correctly. If you need something lightweight that runs fast then I still recommend the V1 script as it does ok. If you think you’re getting falsely flagged VFRs or CFRs then use V2.

V1, runs quickly but is inaccurate. Might incorrectly label a VFR as CFR.

Detection

If all you want to do is detect whether a video is VFR so you can decide whether or not to use it, then all you need is this python script [and python installed, and ffmpeg on your path. If you don’t know what that means, this tool is probably not for you anyways.] Feel free to edit it to make it swear at you less.

VFR Detector
import subprocess
from pathlib import Path
import tkinter as tk
from tkinter import filedialog


def get_video_path():
  root = tk.Tk()
  root.withdraw()
  root.attributes("-topmost", True)
  print("Opening file explorer... Select a video file.")
  path = filedialog.askopenfilename(
      title="Find your fucking file",
      filetypes=[("Video Files", "*.mp4 *.mkv *.avi *.mov *.flv *.webm *.m4v"), ("All Files", "*.*")],
  )
  return Path(path) if path else None


def check_vfr(video_path: Path):
  if not video_path or not video_path.exists():
    print("You didn't fucking pick anything. Exiting.")
    return

  print(f"\nAnalyzing: {video_path.name}\n")

  cmd = [
      "ffprobe",
      "-v",
      "error",
      "-select_streams",
      "v:0",
      "-show_entries",
      "stream=avg_frame_rate,r_frame_rate",
      "-of",
      "default=noprint_wrappers=1:nokey=1",
      str(video_path),
  ]

  try:
    result = subprocess.run(cmd, capture_output=True, text=True, check=True)
    lines = [line.strip() for line in result.stdout.strip().splitlines()]

    if len(lines) < 2:
      print("Could not retrieve frame rate data. This shit is probably broken :( ")
      return

    avg_str, r_str = lines[0], lines[1]
    print(f"--- Analysis Results ---")
    print(f"Average Frame Rate: {avg_str}")
    print(f"Time-Base Rate:     {r_str}")

    def parse_frac(f):
      num, den = map(int, f.split("/")) if "/" in f else (int(float(f)), 1)
      return num, den

    avg_num, avg_den = parse_frac(avg_str)
    r_num, r_den = parse_frac(r_str)

    is_vfr = (avg_str != r_str) or any(val > 100000 for val in (avg_num, avg_den, r_num, r_den))

    if is_vfr:
      print(f"\nResult: This FUCKING video **IS** Variable Frame Rate (VFR). PIECE OF SHIT.")
    else:
      print(f"\nResult: The video **IS NOT** Variable Frame Rate (CFR). :) ")

  except subprocess.CalledProcessError as e:
    print(f"Error running ffprobe... Did you actually install it: {e.stderr.strip()}")
  except Exception as e:
    print(f"Well ... FUCK. An unexpected error occurred: {e}")


if __name__ == "__main__":
  check_vfr(get_video_path())
  input("\nPress Enter to exit...")

But, if you want a real tool for like, gamers and shit.

Detect, Assign FPS, Bash, then Convert to AV1

VFR Resync
import subprocess
from pathlib import Path
import tkinter as tk
from tkinter import filedialog


def get_video_path():
    root = tk.Tk()
    root.withdraw()
    root.attributes("-topmost", True)
    print("Opening file explorer... Select a video file.")
    path = filedialog.askopenfilename(
        title="Select your fucking video",
        filetypes=[("Video Files", "*.mp4 *.mkv *.avi *.mov *.flv *.webm *.m4v"), ("All Files", "*.*")],
    )
    return Path(path) if path else None


def analyze_video(video_path: Path):
    cmd = [
        "ffprobe",
        "-v", "error",
        "-select_streams", "v:0",
        "-show_entries", "stream=avg_frame_rate,r_frame_rate",
        "-of", "default=noprint_wrappers=1:nokey=1",
        str(video_path),
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True, check=True)
    lines = [line.strip() for line in result.stdout.strip().splitlines()]
    
    if len(lines) < 2:
        raise ValueError("Could not retrieve frame rate data from ffprobe. This shit is fucking broken.")

    avg_str, r_str = lines[0], lines[1]
    
    def parse_frac(f):
        return tuple(map(int, f.split("/"))) if "/" in f else (int(float(f)), 1)

    avg_num, avg_den = parse_frac(avg_str)
    r_num, r_den = parse_frac(r_str)
    is_vfr = (avg_str != r_str) or any(val > 100000 for val in (avg_num, avg_den, r_num, r_den))
    avg_fps = avg_num / avg_den if avg_den != 0 else 0.0
    
    return is_vfr, avg_fps


def get_closest_standard_fps(current_fps):
    standard_rates = [24, 25, 30, 48, 50, 60, 120, 144, 240]
    return min(standard_rates, key=lambda x: abs(x - current_fps))


def get_best_av1_encoder():
    print("Can your computer even run this shit?")
    
    # Dictionary of hardware encoders and their respective quality arguments
    encoders = {
        "av1_nvenc": ["-c:v", "av1_nvenc", "-cq", "30", "-b:v", "0", "-preset", "p6"], # NVIDIA
        "av1_amf":   ["-c:v", "av1_amf", "-rc", "cqp", "-qp_p", "30", "-qp_i", "30"],  # AMD
        "av1_qsv":   ["-c:v", "av1_qsv", "-global_quality", "30"],                     # Intel
    }
    
    for enc_name, enc_args in encoders.items():
        # Test command: generates 0.1 seconds of blank video using the specific encoder
        cmd = [
            "ffmpeg", "-v", "error", 
            "-f", "lavfi", "-i", "color=size=1280x720:rate=1:duration=0.1", 
            "-c:v", enc_name, 
            "-f", "null", "-"
        ]
        try:
            # If the return code is 0, the hardware supports this encoder
            result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            if result.returncode == 0:
                print(f"Good news! Your PC isnt a potato. Hardware acceleration found: {enc_name}")
                return enc_args
        except Exception:
            pass

    # If all hardware tests fail, default to CPU
    print("Bad news! Your PC is a potato. No hardware AV1 encoder detected. Falling back to CPU (libsvtav1).")
    return ["-c:v", "libsvtav1", "-crf", "30", "-preset", "6"]


def convert_to_cfr_av1(video_path: Path, target_fps: int, encoder_args: list):
    """Runs the FFmpeg command to convert the video to CFR using AV1."""
    # Automatically generate an output filename
    output_path = video_path.with_name(f"{video_path.stem}_CFR_AV1.mkv")
    
    print(f"\nWe out here converting this shit...")
    print(f"We are put this fucking file here, and if you don't like it get fucked: {output_path}\n")
    
    cmd = [
        "ffmpeg",
        "-i", str(video_path),
        "-r", str(target_fps),
        "-fps_mode", "cfr"       # Replaced -vsync with -fps_mode
    ] + encoder_args + [
        "-c:a", "copy",
        str(output_path)
    ]
    
    try:
        subprocess.run(cmd, check=True)
        print("\nCongrats, it worked!")
    except subprocess.CalledProcessError:
        print("\nError: Bad news! It didn't work. Get fucked.")


def main():
    video_path = get_video_path()
    
    if not video_path or not video_path.exists():
        print("You sidn't select a file. Dumbass.")
        return

    print(f"\nAnalyzing: {video_path.name}")
    
    try:
        is_vfr, avg_fps = analyze_video(video_path)
    except Exception as e:
        print(f"Failed to analyze video, guess this shit is broken: {e}")
        return

    if is_vfr:
        target_fps = get_closest_standard_fps(avg_fps)
        print(f"Bad fucking news: The video **IS** Variable Frame Rate (VFR). That sucks. Time to do a bunch of bullshit to it.")
        print(f"Detected Average Framerate: ~{avg_fps:.2f} fps")
        print(f"Target CFR Framerate:       {target_fps} fps\n")
        
        user_choice = input(f"Would you like to convert this to an AV1 CFR video at {target_fps} fps? You fucking better. (y/n): ").strip().lower()
        
        if user_choice == 'y':
            av1_args = get_best_av1_encoder()
            convert_to_cfr_av1(video_path, target_fps, av1_args)
        else:
            print("What? Am I not good enough for you?")
    else:
        print("Good fucking news: The video **IS NOT** Variable Frame Rate (CFR). You ran this program for nothing :)")


if __name__ == "__main__":
    main()
    input("\nPress Enter to exit...")

You can find both .py files, for now, on this pixeldrain link:

VFR Resync ~ pixeldrain

V2, Detection Update.

UPDATED with significantly better detection.

import os
import re
import subprocess
import tempfile
from pathlib import Path
import tkinter as tk
from tkinter import filedialog


def get_video_path():
    root = tk.Tk()
    root.withdraw()
    root.attributes("-topmost", True)
    print("Pick your video.")
    path = filedialog.askopenfilename(
        title="Click on a fucking video",
        filetypes=[("Video Files", "*.mp4 *.mkv *.avi *.mov *.flv *.webm *.m4v"), ("All Files", "*.*")],
    )
    return Path(path) if path else None


def analyze_video(video_path: Path):
    print(f"\nAnalyzing: {video_path.name}")
    print("Running vfrdet analysis on video stream... This might take a second. Place your thumb up your ass while you wait :)")
    probe_cmd = [
        "ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_entries", "stream=avg_frame_rate",
        "-of", "default=noprint_wrappers=1:nokey=1", str(video_path)
    ]
    probe_res = subprocess.run(probe_cmd, capture_output=True, text=True, check=True)
    avg_str = probe_res.stdout.strip()
    
    if "/" in avg_str:
        num, den = map(int, avg_str.split("/"))
        avg_fps = num / den if den != 0 else 0.0
    else:
        avg_fps = float(avg_str)
    cmd = [
        "ffmpeg",
        "-i", str(video_path),
        "-vf", "vfrdet",
        "-f", "null",
        "-"
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    stderr_output = result.stderr
    
    match = re.search(r"VFR:\s*([0-9.]+)", stderr_output)
    
    if not match:
        raise ValueError("Could not read vfrdet output metrics from FFmpeg. Something is broken :( FUCKKKKKKKK")
        
    vfr_ratio = float(match.group(1))
    
    print(f"\n--- VFR Analysis Metrics ---")
    print(f"VFR Fluctuation Ratio: {vfr_ratio:.6f}")
    is_vfr = vfr_ratio > 0.0
    
    return is_vfr, avg_fps


def get_closest_standard_fps(current_fps):
    standard_rates = [24, 25, 30, 48, 50, 60, 120, 144, 240]
    return min(standard_rates, key=lambda x: abs(x - current_fps))


def get_best_av1_encoder():
    print("\nCan your pc even run this shit...")
    encoders = {
        "av1_nvenc": ["-c:v", "av1_nvenc", "-cq", "30", "-b:v", "0", "-preset", "p6"], 
        "av1_amf":   ["-c:v", "av1_amf", "-rc", "cqp", "-qp_p", "30", "-qp_i", "30"],  
        "av1_qsv":   ["-c:v", "av1_qsv", "-global_quality", "30"],                     
    }
    
    for enc_name, enc_args in encoders.items():
        cmd = [
            "ffmpeg", "-v", "error", 
            "-f", "lavfi", "-i", "color=size=1280x720:rate=1:duration=0.1", 
            "-c:v", enc_name, "-f", "null", "-"
        ]
        try:
            result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            if result.returncode == 0:
                print(f"Good news, your PC isn't a potato. Hardware acceleration found: {enc_name}")
                return enc_args
        except Exception:
            pass

    print("Bad news, your PC is a potato. No hardware AV1 encoder detected. Falling back to CPU (libsvtav1).")
    return ["-c:v", "libsvtav1", "-crf", "30", "-preset", "6"]


def get_safe_mp4_audio_args(video_path: Path):
    cmd = [
        "ffprobe", "-v", "error", "-select_streams", "a:0",
        "-show_entries", "stream=codec_name", "-of", "default=noprint_wrappers=1:nokey=1",
        str(video_path)
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        audio_codec = result.stdout.strip().lower()
        if not audio_codec:
            return ["-an"]
            
        if audio_codec in ["aac", "mp3", "ac3", "eac3", "alac"]:
            return ["-c:a", "copy"]
        else:
            return ["-c:a", "aac", "-b:a", "256k"]
    except Exception:
        return ["-c:a", "aac", "-b:a", "256k"]


def convert_to_cfr_av1(video_path: Path, target_fps: int, encoder_args: list, audio_args: list):
    output_path = video_path.with_name(f"{video_path.stem}_CFR_AV1.mp4")
    
    if not os.access(output_path.parent, os.W_OK):
        print(f"\nError: You didn't give me permission to write to that folder, you bitch '{output_path.parent}'.")
        print("Please move the video to your Desktop or Documents folder, instead of your system32 drive or something, shit head.")
        return

    print(f"\nWe out here converting and shit...")
    print(f"I'm putting the file right here and you can't fucking stop me: {output_path}\n")
    
    cmd = [
        "ffmpeg", "-i", str(video_path), "-r", str(target_fps), "-fps_mode", "cfr"
    ] + encoder_args + audio_args + [str(output_path)]
    
    try:
        subprocess.run(cmd, check=True)
        print("\nWe did it! Thank fucking god! Conversion successful.")
    except subprocess.CalledProcessError:
        print("\nError: FFmpeg encountered an issue during conversion. Guess this shit isn't going to work ... Get fucked.")


def main():
    video_path = get_video_path()
    if not video_path or not video_path.exists():
        print("You didn't pick a fucking video, you moron. Exiting.")
        return

    try:
        is_vfr, avg_fps = analyze_video(video_path)
    except Exception as e:
        print(f"\nFailed to analyze video, this shit is fucking broken: {e}")
        return

    if is_vfr:
        target_fps = get_closest_standard_fps(avg_fps)
        print(f"\nResult: The video **IS** Variable Frame Rate (VFR). PIECE OF SCUM FUCKING SHIT")
        print(f"Detected Average Framerate: ~{avg_fps:.2f} fps")
        print(f"Target CFR Framerate:       {target_fps} fps\n")
        
        user_choice = input(f"Would you like us to be converterizing this shit to AV1 CFR video and shit at {target_fps} fps? You fucking better. (y/n): ").strip().lower()
        
        if user_choice == 'y':
            av1_args = get_best_av1_encoder()
            audio_args = get_safe_mp4_audio_args(video_path)
            convert_to_cfr_av1(video_path, target_fps, av1_args, audio_args)
        else:
            print("What? Am I not good enough for you?")
    else:
        print(f"\nResult: Good news! The video **IS NOT** Variable Frame Rate (CFR). You ran this script for no reason :)")


if __name__ == "__main__":
    main()
    input("\nPress Enter to GET THE FUCK OUT OF MY PROGRAM...")

Or download the updated, V2 version here:
VFRScriptResyncV2.py ~ pixeldrain

UPDATE AGAIN!: @roa sent me a video that was not VFR but still had significant desync. Turns out it was yet another issue that @g90ak had already told me about. In this case, frame duplication. I can’t be assed to write code that detects frame duplication, but if your video has desync, and it’s NOT VFR, it very well could be an issue with frame duplication. The solution is decimation of duplicate frames; specifically decimation followed immediately by the FPS conversion process above since frame decimation essentially creates VFR video. Frame duplication is mainly an issue for older video recorded before dvd, but who honestly knows where else it might happens since video archiving is so bad on the web (looking at you pornhub, you motherfucker.)

Here’s examples of the result from this decimation process on a non-VFR, desynced video:

original


vs. resynced + decimated

Here’s the code, in the very likely case I don’t keep the pixeldrain up and running:

import os
import re
import subprocess
import tempfile
from pathlib import Path
import tkinter as tk
from tkinter import filedialog


def get_video_path():
    root = tk.Tk()
    root.withdraw()
    root.attributes("-topmost", True)
    print("Pick your video.")
    path = filedialog.askopenfilename(
        title="Click on a fucking video",
        filetypes=[("Video Files", "*.mp4 *.mkv *.avi *.mov *.flv *.webm *.m4v"), ("All Files", "*.*")],
    )
    return Path(path) if path else None


def analyze_video(video_path: Path):
    print(f"\nAnalyzing: {video_path.name}")
    print("Running VFR detection analysis on your video. This may take a while. Place your thumb up your ass while you wait :)")
    
    probe_cmd = [
        "ffprobe", "-v", "error", "-select_streams", "v:0",
        "-show_entries", "stream=avg_frame_rate,r_frame_rate",
        "-of", "default=noprint_wrappers=1:nokey=1", str(video_path)
    ]
    probe_res = subprocess.run(probe_cmd, capture_output=True, text=True, check=True)
    lines = [line.strip() for line in probe_res.stdout.strip().splitlines()]
    
    avg_str = lines[0] if len(lines) > 0 else "30/1"
    
    def parse_frac(f):
        return tuple(map(int, f.split("/"))) if "/" in f else (int(float(f)), 1)

    avg_num, avg_den = parse_frac(avg_str)
    avg_fps = avg_num / avg_den if avg_den != 0 else 0.0

    cmd = [
        "ffmpeg",
        "-i", str(video_path),
        "-vf", "vfrdet",
        "-f", "null",
        "-"
    ]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    stderr_output = result.stderr
    
    match = re.search(r"VFR:\s*([0-9.]+)", stderr_output)
    
    if not match:
        raise ValueError("Could not read vfrdet output metrics from FFmpeg.This shit is fucking broken.")
        
    vfr_ratio = float(match.group(1))
    
    print(f"\n--- VFR Analysis Metrics ---")
    print(f"VFR Fluctuation Ratio: {vfr_ratio:.6f}")
    
    is_vfr = vfr_ratio > 0.0
    return is_vfr, avg_fps


def get_closest_standard_fps(current_fps):
    standard_rates = [24, 25, 30, 48, 50, 60, 120, 144, 240]
    return min(standard_rates, key=lambda x: abs(x - current_fps))


def get_best_av1_encoder():
    print("\nCan your pc even run this shit...")
    encoders = {
        "av1_nvenc": ["-c:v", "av1_nvenc", "-cq", "30", "-b:v", "0", "-preset", "p6"], 
        "av1_amf":   ["-c:v", "av1_amf", "-rc", "cqp", "-qp_p", "30", "-qp_i", "30"],  
        "av1_qsv":   ["-c:v", "av1_qsv", "-global_quality", "30"],                     
    }
    
    for enc_name, enc_args in encoders.items():
        cmd = [
            "ffmpeg", "-v", "error", 
            "-f", "lavfi", "-i", "color=size=1280x720:rate=1:duration=0.1", 
            "-c:v", enc_name, "-f", "null", "-"
        ]
        try:
            result = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            if result.returncode == 0:
                print(f"Good news, your PC isn't a potato. Hardware acceleration found: {enc_name}")
                return enc_args
        except Exception:
            pass

    print("Bad news, your PC is a potato. No hardware AV1 encoder detected. Falling back to CPU (libsvtav1).")
    return ["-c:v", "libsvtav1", "-crf", "30", "-preset", "6"]


def get_safe_mp4_audio_args(video_path: Path):
    cmd = [
        "ffprobe", "-v", "error", "-select_streams", "a:0",
        "-show_entries", "stream=codec_name", "-of", "default=noprint_wrappers=1:nokey=1",
        str(video_path)
    ]
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        audio_codec = result.stdout.strip().lower()
        if not audio_codec:
            return ["-an"]
            
        if audio_codec in ["aac", "mp3", "ac3", "eac3", "alac"]:
            return ["-c:a", "copy"]
        else:
            return ["-c:a", "aac", "-b:a", "256k"]
    except Exception:
        return ["-c:a", "aac", "-b:a", "256k"]


def convert_video(video_path: Path, target_fps: int, use_decimate: bool, encoder_args: list, audio_args: list):
    suffix_tag = "Decimated_AV1" if use_decimate else "CFR_AV1"
    output_path = video_path.with_name(f"{video_path.stem}_{suffix_tag}.mp4")
    
    if not os.path.関節(output_path.parent, os.W_OK) if hasattr(os, '関節') else not os.access(output_path.parent, os.W_OK):
        print(f"\nError: You didn't give me permission to write to that folder, you bitch '{output_path.parent}'.")
        print("Please move the video to your Desktop or Documents folder, instead of your system32 drive or something, shit head.")
        return

    print(f"\nWe out here converting and shit...")
    if use_decimate:
        print("[NOTICE] Decimation intiating, we are deleting these fucking frames, HELL YEAH MOTHER FUCKER...")
    
    print(f"I'm putting the file right here and you can't fucking stop me: {output_path}\n")
   
    if use_decimate:
        filter_complex = f"mpdecimate,setpts=N/FRAME_RATE/TB,fps={target_fps}"
    else:
        filter_complex = f"fps={target_fps}"

    cmd = [
        "ffmpeg", "-i", str(video_path),
        "-vf", filter_complex, 
        "-fps_mode", "cfr"
    ] + encoder_args + audio_args + [str(output_path)]
    
    try:
        process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL, text=True)
        
        dropped_frames = 0
        for line in process.stderr:
            print(line, end="")
            if "drop_count" in line or "due to decimation" in line.lower():
                dropped_frames += 1

        process.wait()
        
        if process.returncode != 0:
            raise subprocess.CalledProcessError(process.returncode, cmd)
            
        print(f"\n--- Conversion & Resync Complete ---")
        if use_decimate:
            print(f"Congrats, we decimated the fuck out of this shit, then converted it to CFR: {output_path.name}")
        else:
            print(f"File successfully converted to CFR: {output_path.name}")
            
    except subprocess.CalledProcessError:
        print("\nError: FFmpeg encountered an issue during conversion. Guess this shit isn't going to work ... Get fucked.")


def main():
    video_path = get_video_path()
    if not video_path or not video_path.exists():
        print("You didn't pick a fucking video, you moron. Exiting.")
        return

    try:
        is_vfr, avg_fps = analyze_video(video_path)
    except Exception as e:
        print(f"\nFailed to analyze video, this shit is fucking broken: {e}")
        return

    target_fps = get_closest_standard_fps(avg_fps)

    if is_vfr:
        print(f"\nResult: The video **IS** Variable Frame Rate (VFR). PIECE OF SCUM FUCKING SHIT")
        print(f"Detected Average Framerate: ~{avg_fps:.2f} fps")
        print(f"Target CFR Framerate:       {target_fps} fps\n")
        
        user_choice = input(f"Would you like us to be converterizing this shit to AV1 CFR video and shit at {target_fps} fps? You fucking better. (y/n): ").strip().lower()
        
        if user_choice == 'y':
            av1_args = get_best_av1_encoder()
            audio_args = get_safe_mp4_audio_args(video_path)
            convert_video(video_path, target_fps, use_decimate=False, encoder_args=av1_args, audio_args=audio_args)
        else:
            print("What? Am I not good enough for you?")
    else:
        print(f"\nResult: Good news! The video **IS NOT** Variable Frame Rate (CFR). Happy days!")
        print(f"Detected Framerate: ~{avg_fps:.2f} fps (Target: {target_fps} fps)\n")
        
        decimate_choice = input("If your shit is still desynced, would you like to try to decimate redundant frames in order to attempt a resync? This will also result in a smaller file. (y/n): ").strip().lower()
        
        if decimate_choice == 'y':
            av1_args = get_best_av1_encoder()
            audio_args = get_safe_mp4_audio_args(video_path)
            convert_video(video_path, target_fps, use_decimate=True, encoder_args=av1_args, audio_args=audio_args)
        else:
            print("What? Am I not fucking good enough for you? After all we've been through, you treat me like THIS?")


if __name__ == "__main__":
    main()
    input("\nPress Enter to GET THE FUCK OUT OF MY PROGRAM...")

Here’s the pixeldrain, yet again:

And of course, if this is useful to you, here’s a tip jar haha
https://payhip.com/b/0bwS3

PS: If you find a video that can’t be resynced to a script after using this python code, and moving the points on the funscript doesn’t work, please either post below or send me a DM. It’d be cool if this script could somehow fix all the desync issues. At the very least it has fixed 2 … on two videos.

4 Likes

Didn’t mention in the post above, but I wrote this code while intoxicated and have no intention of bugfixing. Hopefully it works for you! I’m going to bed now

EDIT: I woke up sober and intend to do a little bug fixing

EDIT EDIT: I did a lot more than a little bug fixing.

Nice, good this is hunted down. Will ask @k00gar to pretty please integrate in my favorite scripting toy so its identified and maybe corrected in the library already.

Question is this really just variable FPS or will a script made for 24 FPS played on a 30 FPS movie be out of sync over time?

Video files with different CFRs still remain in sync as far as I can tell.

Updated to V2, will actually detect like 99.9999% of VFR files now. My shitcode was shit originally ;)

deshitified LOL

1 Like

Just updated to a V3 that decimates frames and can resync some videos that are not VFR.

1 Like

I am now working on a directory scanning tool so people can see what files they own are VFR easily. Just scanned my video directory with the prototype and…

OH NO

Sorry no cant put my finger inside that long.

The comments in your code are so damn funny. You’re hell of a writer man!

1 Like

I genuinely have no idea if anyone will ever find these tools useful, but I’ve enjoyed making them.

working on another one right now that allows you to take a script that is perfectly synced to its original video and desynced to another and sync it to the new video because I once again found more videos than can’t be fixed with this VFR+Duplicate frame solution.

This method uses a “piecewise anchor map” that matches video frames between the two videos and creates a table of their different timescales, then warps the funscript time values to match the new video. “IN THEORY” it could allow automated syncing between video sources of all types, and even work around things like one video having the pornhub splashscreen. In theory. Highly unlikely. But so far it’s fixed 1 HD upscale desync that I couldn’t solve otherwise, so that’s neet.

This will 100% be the last one I do because it is making me suicidal.

1 Like

What is the problem upscalers are producing here John? Maybe you should write a howto on how to fucking upscale correctly.

1 Like

Posting a link for posterity, and in case someone needs to find it

1 Like