#!/usr/bin/env python3
"""Print the length in seconds of the data file belonging to a SigMF recording.

Usage: sigmf_duration.py <file.sigmf-meta | file.sigmf-data | basename>

Reads only the JSON metadata (datatype, num_channels, sample_rate) and the size
of the .sigmf-data file, so the sigmf package is not needed.
"""
import json
import os
import re
import sys


def base_name(path):
    for ext in (".sigmf-meta", ".sigmf-data"):
        if path.endswith(ext):
            return path[:-len(ext)]
    return path


def bytes_per_sample(datatype):
    """Bytes per sample per channel for a SigMF datatype such as ci16_le or rf32_le."""
    m = re.fullmatch(r"([cr])([fiu])(8|16|32|64)(_le|_be)?", datatype)
    if not m:
        raise ValueError(f"unknown datatype {datatype!r}")
    complex_, _, bits, _ = m.groups()
    return int(bits) // 8 * (2 if complex_ == "c" else 1)


def duration(path):
    base = base_name(path)
    with open(base + ".sigmf-meta") as f:
        g = json.load(f)["global"]
    frame = bytes_per_sample(g["core:datatype"]) * g.get("core:num_channels", 1)
    return os.path.getsize(base + ".sigmf-data") / frame / g["core:sample_rate"]


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit(__doc__)
    print(f"{duration(sys.argv[1]):.6f}")
