// opus2ogg.c - Convert raw Opus packets to Ogg/Opus container
// Reads raw Opus packets from stdin, writes Ogg-wrapped output to stdout
// Usage: sb-rec -r -N source | opus2ogg -c 1 > output.ogg

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdatomic.h>
#include <signal.h>
#include <unistd.h>
#include "sb-send.h"

_Atomic int g_running = 1;

static void sig_handler(int sig) {
    (void)sig;
    atomic_store(&g_running, 0);
}

int main(int argc, char **argv) {
    int channels = 1;

    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-c") == 0 && i + 1 < argc) {
            channels = atoi(argv[++i]);
        } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
            fprintf(stderr, "Usage: %s [-c channels] < input.rawopus > output.ogg\n", argv[0]);
            return 0;
        }
    }

    struct sigaction sa = { .sa_handler = sig_handler };
    sigemptyset(&sa.sa_mask);
    sigaction(SIGINT, &sa, NULL);
    sigaction(SIGTERM, &sa, NULL);

    OggWriter ogg;
    ogg_writer_init(&ogg, channels, "sb-rec", stdout);

    unsigned char pkt[4096];
    while (atomic_load(&g_running)) {
        uint32_t pkt_len = 0;
        if (fread(&pkt_len, 4, 1, stdin) != 1) {
            break;
        }
        if (pkt_len > sizeof(pkt)) {
            break;
        }
        if (pkt_len > 0 && fread(pkt, 1, pkt_len, stdin) != pkt_len) {
            break;
        }
        ogg_writer_packet(&ogg, pkt, pkt_len, stdout);
    }

    ogg_writer_finish(&ogg, stdout);
    return 0;
}
