#! /usr/bin/python

import subprocess, argparse

def main():
    parser = argparse.ArgumentParser(description='Call ffmpeg for converting small video files to mp4 or webp')
    parser.add_argument('input', help='input file or url')
    parser.add_argument('output', help='output filename')
    parser.add_argument('-s', '--start', help='start time, if not 00:00')
    parser.add_argument('-t', '--to', help='end time, if not end of file')
    parser.add_argument('-q', '--quality', help='quality of output, as a percentage')
    parser.add_argument('-S', '--silent', action='store_true', help='no audio')
    parser.add_argument('-c', '--crop', help='out_w:out_h:x:y  Can use in_w and in_h as variables. Top-left is 0:0')
    args = parser.parse_args()
    f_args = []

    if "https" in args.input:
        # get direct urls from youtube-dl
        urls = subprocess.run(["yt-dlp", "--get-url", args.input], capture_output=True, encoding='utf-8')
        for url in urls.stdout.split('\n'):
            if len(url) > 10:
                f_args += ["-i", url]
    else:
        # local file, or single local http stream
        f_args += ["-i", args.input]

    vfilter = "scale=-2:'min(720,ih)'"
    if args.crop:
        vfilter += f",crop={args.crop}"
    f_args += ["-vf", vfilter]

    if args.start:
        f_args += ["-ss", args.start]
    if args.to:
        f_args += ["-to", args.to]
    if args.silent:
        f_args += ["-an"]
    f_args += ["-sn"]
    f_args += ["-dn"]
    f_args += ["-map_metadata:c", "-1"]

    if ".webp" in args.output:
        f_args += ["-vcodec", "libwebp"]
        f_args += ["-preset", "default"]
        f_args += ["-loop", "0", "-an", "-vsync", "0"]
        f_args += ["-qscale", args.quality if args.quality else "70"]
    else:
        f_args += ["-c:v", "libx264"]
        f_args += ["-preset", "veryfast"]
        f_args += ["-crf", "26"]
        f_args += ["-c:a", "aac"]
        f_args += ["-b:a", "128k"]
        f_args += ["-pix_fmt", "yuv420p"]
    print(f_args)

    subprocess.run(["ffmpeg", "-y"] + f_args + [args.output if args.output else "output.mp4"])

if __name__ == "__main__":
    main()
