#!/usr/bin/python3

"""Test encoding, probing, decoding and stream copying with FFmpeg."""

import itertools
import json
import os
import re
import shlex
import subprocess
import sys
from collections.abc import Sequence
from pathlib import Path
from tempfile import TemporaryDirectory

CODEC_OPTIONS = {
    "avui": ["-s", "720x486"],
    "dnxhd": ["-s", "1280x720", "-b:v", "90M", "-pix_fmt", "yuv422p"],
    "dvvideo": ["-s", "720x480", "-pix_fmt", "yuv411p"],
    "h261": ["-s", "176x144"],
    "h263": ["-s", "128x96"],
    "hevc": ["-s", "64x64"],
    "roq": ["-s", "128x128"],
    "xface": ["-s", "48x48"],
    "g723_1": ["-ar", "8000", "-b:a", "6300"],
    "gsm": ["-ar", "8000", "-b:a", "13000"],
    "gsm_ms": ["-ar", "8000", "-b:a", "13000"],
    "roq_dpcm": ["-ar", "22050"],
    "s302m": ["-ac", "2"],
    "vorbis": ["-ac", "2"],
}
SOURCES = {"v": "testsrc=s=32x32:d=0.5", "a": "sine=d=0.5"}


def return_code(code: int) -> int:
    """Report signal termination using the shell's 128 + signal convention."""
    return 128 - code if code < 0 else code


def run(command: Sequence[str | Path]) -> int:
    print(shlex.join(str(arg) for arg in command), flush=True)
    result = subprocess.run(command, stderr=subprocess.STDOUT, check=False)
    return return_code(result.returncode)


def list_muxers() -> set[str]:
    output = subprocess.check_output(["ffmpeg", "-hide_banner", "-formats"], text=True)
    # The optional third flag marks devices in newer FFmpeg versions.
    return {
        match.group(1).split(",")[0]
        for line in output.splitlines()
        if (match := re.match(r"^ [D ]E[ d]? +([^ =]+) +", line))
    }


def list_encoders() -> set[str]:
    output = subprocess.check_output(["ffmpeg", "-hide_banner", "-codecs"], text=True)
    encoders: dict[str, list[str]] = {"V": [], "A": []}
    for line in output.splitlines():
        match = re.match(r"^ .E([VA])\S* +(\S+) +(.*)", line)
        if not match:
            continue
        kind, codec, description = match.groups()
        names = re.search(r"\(encoders: ([^)]*)\)", description)
        if names:
            encoders[kind].extend(
                f"{kind.lower()}={codec}:{name}" for name in names[1].split()
            )
        else:
            encoders[kind].append(f"{kind.lower()}={codec}")
    return set(encoders["V"] + encoders["A"])


def read_tests(filename: Path) -> list[tuple[str, str, bool]]:
    tests: list[tuple[str, str, bool]] = []
    for line in filename.read_text().splitlines():
        muxer, _, encoders = line.partition(";")
        for encoder in encoders.split():
            name, _, streamcopy = encoder.partition("|")
            tests.append((muxer, name, streamcopy == "1"))
    return tests


def encode_file(
    muxer: str,
    kind: str,
    codec: str,
    encoder: str,
    filename: Path,
    threads: int,
) -> int:
    print(
        f"trying muxer '{muxer}' with '{kind}' encoder '{encoder}' "
        f"for codec '{codec}'\n"
    )

    if kind not in SOURCES:
        return 10

    return run(
        [
            "ffmpeg",
            "-threads",
            str(threads),
            "-f",
            "lavfi",
            "-i",
            SOURCES[kind],
            "-strict",
            "-2",
            *CODEC_OPTIONS.get(codec, []),
            f"-c:{kind}",
            encoder,
            "-f",
            muxer,
            filename,
            "-y",
            "-hide_banner",
            "-nostdin",
        ]
    )


def probe_file(filename: Path, muxer: str, codec: str) -> tuple[int, str]:
    result = subprocess.run(
        [
            "ffprobe",
            "-hide_banner",
            "-strict",
            "-2",
            "-v",
            "error",
            "-show_entries",
            "format=format_name:stream=codec_name",
            "-of",
            "json",
            filename,
        ],
        capture_output=True,
        text=True,
        check=False,
    )

    if result.returncode:
        code = return_code(result.returncode)
        return code, f"probing failed: {code}"

    info = json.loads(result.stdout)
    formats = info.get("format", {}).get("format_name", "").split(",")
    codecs = [stream.get("codec_name", "") for stream in info.get("streams", [])]
    if muxer not in formats:
        return 10, f"file has the wrong format: {' '.join(formats)}"
    if codec not in codecs:
        return 11, f"file has the wrong codec: {' '.join(codecs)}"

    return 0, ""


def decode_file(filename: Path, threads: int) -> int:
    # Limit duration because the comfortnoise decoder never stops producing noise.
    return run(
        [
            "ffmpeg",
            "-threads",
            str(threads),
            "-strict",
            "-2",
            "-i",
            filename,
            "-t",
            "1",
            "-c:v",
            "rawvideo",
            "-c:a",
            "pcm_s32le",
            "-f",
            "nut",
            "/dev/null",
            "-y",
            "-hide_banner",
            "-nostdin",
        ]
    )


def streamcopy_file(
    filename: Path, muxer: str, copy_filename: Path, threads: int
) -> int:
    # Keep the same duration limit as decoding.
    return run(
        [
            "ffmpeg",
            "-threads",
            str(threads),
            "-strict",
            "-2",
            "-i",
            filename,
            "-t",
            "1",
            "-c",
            "copy",
            "-f",
            muxer,
            copy_filename,
            "-y",
            "-hide_banner",
            "-nostdin",
        ]
    )


def main() -> bool:
    script = Path(__file__).resolve()
    test_name = sys.argv[1] if len(sys.argv) > 1 else "encdec_list.txt"
    test_list = script.with_name(test_name)
    update = not test_list.is_file()

    print(f"TEST: {test_name}")
    print(f"AUTOPKGTEST_TMP directory: {os.environ['AUTOPKGTEST_TMP']}\n\n")

    muxers = list_muxers()
    encoders = list_encoders()
    print(f"\nmuxers:\n{' '.join(muxers)}\n\n")
    print(f"encoders:\n{' '.join(encoders)}\n\n")

    tests = (
        [
            (muxer, encoder, True)
            for muxer, encoder in itertools.product(muxers, encoders)
        ]
        if update
        else read_tests(test_list)
    )
    print(f"{len(tests)} tests\n")

    crashes: list[str] = []
    failures: list[str] = []
    skipped: list[str] = []
    generated: dict[str, list[str]] = {}
    successes = 0

    def failed(test: str, code: int, message: str) -> None:
        error = f"{test}; {message}"
        if code > 128:
            crashes.append(error)
        else:
            failures.append(error)
        print(f"\nFAILED: {error}\n\n")

    with TemporaryDirectory(dir=Path(os.environ["AUTOPKGTEST_TMP"])) as test_dir:
        threads = min(8, len(os.sched_getaffinity(0)))

        for number, (muxer, typed_encoder, copy_requested) in enumerate(tests, 1):
            test = f"{muxer};{typed_encoder}"
            print(f"Test {number}:")
            if muxer not in muxers or typed_encoder not in encoders:
                skipped.append(test)
                print(f"SKIPPED: {test}\n\n")
                continue

            kind, encoding = typed_encoder.split("=", 1)
            codec, _, encoder = encoding.partition(":")
            encoder = encoder or codec
            filename = Path(test_dir) / f"{encoder}.{muxer}"
            if muxer == "hls":
                filename = filename.with_suffix(".hls.m3u8")

            # encode file
            code = encode_file(muxer, kind, codec, encoder, filename, threads)
            print("\n")
            if code:
                failed(test, code, f"encoding return code: {code}")
                continue

            # try to probe encoded file
            code, error = probe_file(filename, muxer, codec)
            if code:
                failed(test, code, error)
                continue

            # decode file
            code = decode_file(filename, threads)
            if code:
                failed(test, code, f"decoding return code: {code}")
                continue

            # try to copy
            copy_works = True
            if copy_requested:
                copy_filename = Path(f"{filename}.copy.{muxer}")
                if muxer == "hls":
                    copy_filename = Path(f"{copy_filename}.m3u8")
                print("\n")
                code = streamcopy_file(filename, muxer, copy_filename, threads)
                if code:
                    failed(test, code, f"streamcopy return code: {code}")
                    copy_works = False
                else:
                    code, error = probe_file(copy_filename, muxer, codec)
                    if code:
                        failed(test, code, f"streamcopy: {error}")
                        copy_works = False

            if copy_requested and copy_requested == copy_works:
                works = "works" if copy_works else "fails"
                print(
                    f"\nSUCCESS: correctly created file with format '{muxer}' and "
                    f"codec '{typed_encoder}'; streamcopying {works}\n\n"
                )
                successes += 1

            if update:
                generated.setdefault(muxer, []).append(
                    f"{typed_encoder}|{int(copy_works)}"
                )

        print("done!")

    if generated:
        test_list.write_text(
            "".join(
                f"{muxer}; {' '.join(sorted(entries))}\n"
                for muxer, entries in sorted(generated.items())
            )
        )

    for label, entries in [
        ("crashes", crashes),
        ("failures", failures),
        ("skipped", skipped),
    ]:
        if entries:
            print(f"\n\n{label}: {len(entries)}\n")
            print("\n".join(entries))

    if successes:
        print(f"\n\nsuccess: {successes}\n")
    else:
        print("\n\nno single success: something is definitely wrong\n")

    return bool(crashes or failures or not successes)


if __name__ == "__main__":
    sys.exit(int(main()))
