/*
 * webrtcDeviceSample.c
 *
 * "Device" (callee) counterpart to user-client.html, speaking to
 * signaling-server.js over a PLAIN WebSocket using our own minimal JSON
 * protocol - NOT the built-in Signaling module. This is the
 * "write your own signaling transport" path: PeerConnection/ICE/DTLS-SRTP
 * come from webrtcClient as usual, but SDP/ICE exchange rides over a
 * hand-rolled libwebsockets client instead of Signaling.c.
 *
 * Protocol (mirrors device-hdl.js / user-hdl.js, minus STOMP/JWT/TURN-REST):
 *   Connect:    ws://<host>:<port>/ws
 *   Register:   {"type":"REGISTER","clientType":"device","clientId":"<deviceId>"}
 *   Envelope:   {"callId","msgType":REQUEST|RESPONSE,"command":INVITE|HANGUP|P2P_HANDSHAKE,
 *                "userId","content":{...}}
 *   Handshake:  content = {"method":OFFER|ANSWER|ICE_CANDIDATE,"content":<sdp-or-candidate>}
 *
 * On INVITE: auto-accept (single concurrent call), create PeerConnection with
 * a sendrecv H264 video transceiver (+ a "chat" data channel), plus a
 * sendrecv G.711 PCMU audio transceiver when the INVITE asks for audio
 * (content.audio=true; absent/false = video only, no m=audio at all).
 * On OFFER: setRemoteDescription -> createAnswer -> setLocalDescription -> send ANSWER.
 * On ICE_CANDIDATE: addIceCandidate.
 * Once RTC_PEER_CONNECTION_STATE_CONNECTED: send video (static H264 frames or the
 * GStreamer source) and, if requested, a synthetic 1 kHz G.711 PCMU tone.
 *
 * Build: link against webrtcClient + libwebsockets + normal SDK deps
 * (openssl/mbedtls, libsrtp2, usrsctp, pthread). NOT webrtcSignalingClient.
 *
 * Run:
 *   ./webrtcDeviceSample [deviceId] [signalingHost] [signalingPort] [mediaSource] [options]
 *   ./webrtcDeviceSample device-1 localhost 8080
 *   ./webrtcDeviceSample device-1 localhost 8080 testsrc
 *   ./webrtcDeviceSample device-1 localhost 8080 testsrc --resolution=1280x720 --fps=30 --bitrate=4000
 *   ./webrtcDeviceSample device-1 localhost 8080 file --fps=15 --h264-dir=./h264
 *   ./webrtcDeviceSample --help
 *
 * mediaSource selects where outgoing media comes from once a call connects:
 *   file (default) - loop static frames from h264Dir, as before.
 *   testsrc         - GStreamer videotestsrc, x264-encoded.
 *
 * --h264-dir= points at the static sample-frame directory (only used by
 * "file"; default ./h264SampleFrames).
 * --fps=/--bitrate=/--resolution=WxH are common video options shared by both
 * media sources (see printUsage()/parseArgs()): --fps paces frame sending
 * for "file" and sets the pipeline framerate for "testsrc"; --bitrate and
 * --resolution only affect "testsrc" since "file" streams pre-encoded
 * sample frames whose encoding is already fixed. Defaults: 2560x1440
 * @30fps, 13000 kbps. See GstMedia.c in the SDK samples for the pipeline
 * strings this mirrors.
 *
 * Simplifications vs. a production system: no TLS, no auth, no TURN
 * credential provisioning, one call at a time, and a JSON parser that's
 * purpose-built for this fixed message shape rather than general-purpose.
 */

/*
 * TC02 - Streaming throughput (device side), derived from webrtcDeviceSample.c
 *
 * Differences from the sample:
 *  - GStreamer videotestsrc is the default (and intended) media source. Video parameters
 *    (width/height/fps/bitrate) are read from the client's INVITE:
 *        "content":{"callType":"VIDEO","video":{"width":1280,"height":720,"fps":30,"bitrate":2000}}
 *    Missing/invalid values fall back to the CLI defaults (--resolution/--fps/--bitrate).
 *    The applied values are echoed in the INVITE 200 response.
 *  - ICE and audio are also configured per call by the INVITE (no command-line options):
 *        "stunUrl", "turnUrl", "turnUser", "turnPass", "iceTransportPolicy" ("all"|"relay") at the top level,
 *        "content":{"audio":true|false}
 *    A STUN/TURN field that is absent falls back to DEFAULT_STUN_URL / DEFAULT_TURN_*; one that is present
 *    but empty means "none" (e.g. turnUrl:"" = no TURN server). iceTransportPolicy defaults to "all" and
 *    audio to off. Audio is a synthetic 1 kHz G.711 PCMU tone (what the TC02 client negotiates).
 *  - Static-file mode (mediaSource=file + --profiles-dir=ROOT) avoids the x264 CPU cost: pre-encoded
 *    frames are loaded into RAM per call from ROOT/<W>x<H>_<FPS>fps_<KBPS>kbps/frame-NNNN.h264 (the
 *    directory is chosen from the INVITE's video config; no match -> INVITE answered 404). Generate
 *    the folders with gen_h264_profiles.py.
 *  - Parallel calls: up to --max-calls (default 8) concurrent calls, one slot each (own peer connection,
 *    video source, stats thread and data channel). CPU/RSS in DEVICE_STATS are process-wide.
 *  - The client creates a data channel; once connected the device sends a DEVICE_STATS JSON
 *    message on it every second (CPU %, RSS, encoder/sender bitrate + fps, frame drops, ...)
 *    and prints the same line on stdout as [Device][TC02].
 *  - HANGUP is answered with a RESPONSE (the client waits for it), only tears down the
 *    matching callId, and a stuck call is closed on peer FAILED/CLOSED or by a watchdog
 *    (--call-watchdog=SEC, default 900, 0 = off) so the device never stays BUSY forever.
 */
#include <stdio.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdint.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <sys/time.h>

#include <libwebsockets.h>

#include <WebRtcClient.h>

#include <gst/gst.h>
#include <gst/app/gstappsink.h>

#ifndef HUNDREDS_OF_NANOS_IN_A_SECOND
#define HUNDREDS_OF_NANOS_IN_A_SECOND (10 * 1000 * 1000)
#endif

#define MAX_WS_MESSAGE_SIZE 32768
#define MAX_OUTGOING_QUEUE 128 /* several parallel calls trickle ICE at once */
#define MAX_PATH_LEN 256
#define MAX_ID_LEN 128
#define DEFAULT_VIDEO_FPS 30
#define AUDIO_FPS 50 /* 20 ms G.711 PCMU frames, fixed regardless of media source */
#define PCMU_FRAME_BYTES 160 /* 8000 Hz * 20 ms, 1 byte per sample */

/* Fallbacks, used only when the INVITE does not carry the corresponding field. */
#define DEFAULT_STUN_URL "stun:stun.l.google.com:19302"
#define DEFAULT_TURN_URL "turn:127.0.0.1:3478"
#define DEFAULT_TURN_USER "test"
#define DEFAULT_TURN_PASS "test"
#define TESTSRC_VIDEO_PIPELINE_MAX_CHAR_COUNT 640
#define TESTSRC_AUDIO_PIPELINE_MAX_CHAR_COUNT 320
#define TESTSRC_PIPELINE_MAX_CHAR_COUNT (TESTSRC_VIDEO_PIPELINE_MAX_CHAR_COUNT + TESTSRC_AUDIO_PIPELINE_MAX_CHAR_COUNT)

/* Common video config, shared by both media sources and settable via
 * --fps=/--bitrate=/--resolution= flags (see parseArgs()). For
 * MEDIA_SOURCE_STATIC_FILES only fps has an effect (it paces how fast the
 * pre-encoded sample frames are sent); width/height/bitrate are baked into
 * those files already. For MEDIA_SOURCE_GST_TEST all four drive the
 * videotestsrc pipeline directly. */
#define DEFAULT_VIDEO_WIDTH 1080
#define DEFAULT_VIDEO_HEIGHT 720
#define DEFAULT_VIDEO_BITRATE_KBPS 2000

/* Where media comes from. STATIC_FILES preserves the original behaviour
 * (looping ./h264SampleFrames from disk). GST_TEST
 * instead runs a GStreamer videotestsrc pipeline and pushes its encoded
 * output straight into the video transceiver, mirroring GstMedia.c's
 * on_new_sample(). fps/bitrate/resolution are configurable for both modes -
 * see DeviceContext's video* fields and parseArgs(). */
typedef enum
{
    MEDIA_SOURCE_STATIC_FILES,
    MEDIA_SOURCE_GST_TEST,
} MediaSourceType;

/* ---------------------------------------------------------------------- */
/* Global state                                                            */
/* ---------------------------------------------------------------------- */

typedef struct
{
    char data[MAX_WS_MESSAGE_SIZE];
    uint32_t len;
} OutgoingMessage;

/* One pre-loaded H.264 access unit (Annex-B). Static-file mode loads the whole clip into RAM at INVITE
 * so the send loop does no disk I/O and no encoding: CPU then reflects packetize + SRTP + send only. */
typedef struct
{
    uint8_t *data;
    uint32_t size;
    uint32_t isKey;
} StaticFrame;

/* Measures the bitrate actually arriving at an appsink / leaving the send loop (kbps + frames/s per second). */
typedef struct
{
    const char *label;
    uint64_t bytesAccum;
    uint32_t frameCount;
    GstClockTime windowStart;
    uint64_t totalFrames;
    double lastKbps;
    double lastFps;
} BitrateProbeCtx;

/* ICE servers of one call, as requested by the client in the INVITE. Empty string = not used. */
typedef struct
{
    char stunUrl[MAX_ICE_CONFIG_URI_LEN + 1];
    char turnUrl[MAX_ICE_CONFIG_URI_LEN + 1];
    char turnUser[MAX_ICE_CONFIG_CREDENTIAL_LEN + 1];
    char turnPass[MAX_ICE_CONFIG_CREDENTIAL_LEN + 1];
} IceServerConfig;

#define MAX_CALLS_LIMIT 32
#define DEFAULT_MAX_CALLS 8

/* One slot per concurrent call. Slots live in a static array, so a slot pointer is stable and can be handed to
 * GStreamer/SDK callbacks; SDK callbacks get (gen << 8 | index) as customData so a callback that outlives its
 * call (slot already re-used) is recognised as stale and ignored. */
typedef struct
{
    uint32_t index;
    volatile uint64_t gen;
    volatile uint32_t active;
    volatile uint32_t peerFailed;
    volatile uint32_t mediaConnected;
    uint32_t mediaStarted;
    char callId[MAX_ID_LEN];
    char userId[MAX_ID_LEN];
    time_t startTime;

    /* ICE config and audio switch of this call, both from the client's INVITE */
    char icePolicy[16]; /* "all" | "relay" */
    IceServerConfig ice;
    uint32_t audioEnabled;

    /* Video config of this call (from the client's INVITE, else CLI defaults) */
    int32_t width, height, fps, bitrateKbps;

    PRtcPeerConnection peerConnection;
    PRtcRtpTransceiver videoTransceiver;
    PRtcRtpTransceiver audioTransceiver; /* NULL unless audioEnabled */
    PRtcDataChannel dataChannel;

    pthread_t videoThread;
    uint32_t videoThreadStarted;
    pthread_t audioThread;
    uint32_t audioThreadStarted;
    pthread_t statsThread;
    uint32_t statsThreadStarted;

    /* GStreamer source */
    GstElement *gstPipeline;
    pthread_t gstBusThread;
    uint32_t gstBusThreadStarted;
    uint32_t videoFrameIndex;
    uint64_t videoTs;

    /* Static-file source (frames pre-loaded into RAM) */
    char staticDir[MAX_PATH_LEN];
    StaticFrame *staticFrames;
    uint32_t staticFrameCount;

    /* Per-call frame counters ("dropped" = produced but never accepted by writeFrame()) */
    uint64_t framesWritten, framesDropped, writeFailures;
    uint64_t audioFramesWritten, audioFramesDropped;
    BitrateProbeCtx probe;
} CallSlot;

typedef struct
{
    char deviceId[MAX_ID_LEN];
    char signalingHost[MAX_ID_LEN];
    int32_t signalingPort;
    char h264Dir[MAX_PATH_LEN];
    uint64_t h264FrameCount;

    /* CLI defaults; each call may override them through its INVITE */
    MediaSourceType mediaSourceType;
    int32_t videoWidth;
    int32_t videoHeight;
    int32_t videoFps;
    int32_t videoBitrateKbps;
    int32_t defWidth, defHeight, defFps, defBitrateKbps;

    /* TC02 static-file profiles: <profilesRoot>/<W>x<H>_<FPS>fps_<KBPS>kbps/frame-NNNN.h264 */
    char profilesRoot[MAX_PATH_LEN];

    struct lws_context *wsContext;
    struct lws *wsi;
    volatile uint32_t wsConnected;
    volatile uint32_t terminate;

    OutgoingMessage outQueue[MAX_OUTGOING_QUEUE];
    uint32_t outQueueHead;
    uint32_t outQueueTail;
    pthread_mutex_t outQueueLock;

    /* Concurrent calls */
    CallSlot calls[MAX_CALLS_LIMIT];
    uint32_t maxCalls;
    int32_t callWatchdogSec;
    pthread_mutex_t callLock;  /* protects slot allocation / state transitions */
    pthread_mutex_t closeLock; /* serialises closeCall() (HANGUP on the ws thread vs main-loop cleanup) */

    /* CPU/RAM resource monitor (runs for the lifetime of the process) */
    pthread_t resourceMonitorThread;
    uint32_t resourceMonitorThreadStarted;
} DeviceContext, *PDeviceContext;

static DeviceContext gCtx;

static uint32_t activeCallCount(void)
{
    uint32_t i, n = 0;
    for (i = 0; i < gCtx.maxCalls; i++)
    {
        n += gCtx.calls[i].active ? 1 : 0;
    }
    return n;
}

static const char *activeCallLabel(void)
{
    static __thread char label[32];
    snprintf(label, sizeof(label), "%u active", activeCallCount());
    return label;
}

/* ---------------------------------------------------------------------- */
/* Resource monitor (CPU % / RSS via Linux /proc, ported from the IOTC    */
/* p2p tc04 stress-test client) - samples this process's own usage every  */
/* RESOURCE_MONITOR_INTERVAL_SEC and prints a status line, independent of */
/* call/media state so it also covers idle "waiting for INVITE" time.     */
/* ---------------------------------------------------------------------- */

#define RESOURCE_MONITOR_INTERVAL_SEC 1
#define RESOURCE_PRINT_EVERY 5

typedef struct
{
    long vm_size_kb;
    long vm_rss_kb;
    long vm_peak_kb;
    long vm_data_kb;
    long vm_stack_kb;
    long vm_hwm_kb;
} ProcessMemoryInfo;

typedef struct
{
    unsigned long long utime, stime, cutime, cstime, total_time, timestamp;
} ProcessCPUInfo;

typedef struct
{
    ProcessMemoryInfo initial, current, peak;
    uint64_t sample_count;
    struct timeval start_time;
} MemoryMonitor;

typedef struct
{
    ProcessCPUInfo initial, current, previous;
    double current_cpu_percent, peak_cpu_percent, avg_cpu_percent;
    uint64_t sample_count;
    double total_cpu_sum;
    struct timeval start_time;
} CPUMonitor;

static MemoryMonitor gMemMonitor = {0};
static CPUMonitor gCpuMonitor = {0};
static pthread_mutex_t gMonitorLock = PTHREAD_MUTEX_INITIALIZER;

static uint64_t monitorGetTimeUs(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (uint64_t)tv.tv_sec * 1000000 + tv.tv_usec;
}

static long monitorGetClockTicks(void)
{
    static long t = 0;
    if (!t)
    {
        t = sysconf(_SC_CLK_TCK);
        if (t <= 0)
        {
            t = 100;
        }
    }
    return t;
}

static int32_t monitorGetProcessCpu(ProcessCPUInfo *pInfo)
{
    FILE *fp = fopen("/proc/self/stat", "r");
    unsigned long long u, s, cu, cs;
    int32_t r;

    if (fp == NULL)
    {
        return -1;
    }
    /* Skip pid/comm/state/... straight to utime/stime/cutime/cstime (fields 14-17) */
    r = fscanf(fp, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu %llu %llu", &u, &s, &cu, &cs);
    fclose(fp);
    if (r != 4)
    {
        return -1;
    }
    pInfo->utime = u;
    pInfo->stime = s;
    pInfo->cutime = cu;
    pInfo->cstime = cs;
    pInfo->total_time = u + s + cu + cs;
    pInfo->timestamp = monitorGetTimeUs();
    return 0;
}

static double monitorCalculateCpuPercent(ProcessCPUInfo *pPrev, ProcessCPUInfo *pCur)
{
    unsigned long long dt, de;

    if (!pPrev->timestamp || pCur->timestamp == pPrev->timestamp)
    {
        return 0.0;
    }
    dt = pCur->total_time - pPrev->total_time;
    de = pCur->timestamp - pPrev->timestamp;
    if (!de)
    {
        return 0.0;
    }
    return ((double)dt / monitorGetClockTicks()) / (de / 1000000.0) * 100.0;
}

static int32_t monitorGetProcessMemory(ProcessMemoryInfo *pInfo)
{
    FILE *fp = fopen("/proc/self/status", "r");
    char line[256];

    if (fp == NULL)
    {
        return -1;
    }
    memset(pInfo, 0, sizeof(*pInfo));
    while (fgets(line, sizeof(line), fp))
    {
        if (!strncmp(line, "VmSize:", 7))
        {
            sscanf(line + 7, "%ld", &pInfo->vm_size_kb);
        }
        else if (!strncmp(line, "VmRSS:", 6))
        {
            sscanf(line + 6, "%ld", &pInfo->vm_rss_kb);
        }
        else if (!strncmp(line, "VmPeak:", 7))
        {
            sscanf(line + 7, "%ld", &pInfo->vm_peak_kb);
        }
        else if (!strncmp(line, "VmData:", 7))
        {
            sscanf(line + 7, "%ld", &pInfo->vm_data_kb);
        }
        else if (!strncmp(line, "VmStk:", 6))
        {
            sscanf(line + 6, "%ld", &pInfo->vm_stack_kb);
        }
        else if (!strncmp(line, "VmHWM:", 6))
        {
            sscanf(line + 6, "%ld", &pInfo->vm_hwm_kb);
        }
    }
    fclose(fp);
    return 0;
}

static void monitorInitMemory(void)
{
    gettimeofday(&gMemMonitor.start_time, NULL);
    monitorGetProcessMemory(&gMemMonitor.initial);
    gMemMonitor.current = gMemMonitor.initial;
    gMemMonitor.peak = gMemMonitor.initial;
}

static void monitorInitCpu(void)
{
    gettimeofday(&gCpuMonitor.start_time, NULL);
    monitorGetProcessCpu(&gCpuMonitor.initial);
    gCpuMonitor.current = gCpuMonitor.initial;
    gCpuMonitor.previous = gCpuMonitor.initial;
}

static void monitorUpdateMemoryStats(void)
{
    ProcessMemoryInfo cur;

    pthread_mutex_lock(&gMonitorLock);
    if (monitorGetProcessMemory(&cur) == 0)
    {
        gMemMonitor.current = cur;
        gMemMonitor.sample_count++;
        if (cur.vm_rss_kb > gMemMonitor.peak.vm_rss_kb)
        {
            gMemMonitor.peak.vm_rss_kb = cur.vm_rss_kb;
        }
        if (cur.vm_size_kb > gMemMonitor.peak.vm_size_kb)
        {
            gMemMonitor.peak.vm_size_kb = cur.vm_size_kb;
        }
        if (cur.vm_data_kb > gMemMonitor.peak.vm_data_kb)
        {
            gMemMonitor.peak.vm_data_kb = cur.vm_data_kb;
        }
    }
    pthread_mutex_unlock(&gMonitorLock);
}

static void monitorUpdateCpuStats(void)
{
    ProcessCPUInfo cur;

    pthread_mutex_lock(&gMonitorLock);
    if (monitorGetProcessCpu(&cur) == 0)
    {
        double p;

        gCpuMonitor.previous = gCpuMonitor.current;
        gCpuMonitor.current = cur;
        p = monitorCalculateCpuPercent(&gCpuMonitor.previous, &gCpuMonitor.current);
        gCpuMonitor.current_cpu_percent = p;
        if (p > gCpuMonitor.peak_cpu_percent)
        {
            gCpuMonitor.peak_cpu_percent = p;
        }
        gCpuMonitor.sample_count++;
        gCpuMonitor.total_cpu_sum += p;
        gCpuMonitor.avg_cpu_percent = gCpuMonitor.total_cpu_sum / gCpuMonitor.sample_count;
    }
    pthread_mutex_unlock(&gMonitorLock);
}

static void monitorPrintResourceStatus(void)
{
    ProcessMemoryInfo m;
    double cpu;

    pthread_mutex_lock(&gMonitorLock);
    m = gMemMonitor.current;
    cpu = gCpuMonitor.current_cpu_percent;
    pthread_mutex_unlock(&gMonitorLock);
    printf("[Device][Resources] CPU: %5.1f%% | RSS: %6.2f MB | VmSize: %7.2f MB | Data: %6.2f MB | Call: %s\n",
           cpu, m.vm_rss_kb / 1024.0, m.vm_size_kb / 1024.0, m.vm_data_kb / 1024.0,
           activeCallLabel());
}

static void monitorPrintMemoryReport(void)
{
    ProcessMemoryInfo cur, ini, pk;

    pthread_mutex_lock(&gMonitorLock);
    cur = gMemMonitor.current;
    ini = gMemMonitor.initial;
    pk = gMemMonitor.peak;
    pthread_mutex_unlock(&gMonitorLock);
    printf("\n===================== MEMORY USAGE REPORT =====================\n");
    printf(" RSS   Initial: %8ld KB  Current: %8ld KB  Peak: %8ld KB\n", ini.vm_rss_kb, cur.vm_rss_kb, pk.vm_rss_kb);
    printf(" Delta: %+8ld KB (%+7.2f MB)\n", cur.vm_rss_kb - ini.vm_rss_kb, (cur.vm_rss_kb - ini.vm_rss_kb) / 1024.0);
    printf("=================================================================\n\n");
}

static void monitorPrintCpuReport(void)
{
    double curCpu, avgCpu, pkCpu;

    pthread_mutex_lock(&gMonitorLock);
    curCpu = gCpuMonitor.current_cpu_percent;
    avgCpu = gCpuMonitor.avg_cpu_percent;
    pkCpu = gCpuMonitor.peak_cpu_percent;
    pthread_mutex_unlock(&gMonitorLock);
    printf("======================= CPU USAGE REPORT =======================\n");
    printf(" Current: %7.2f%%  Average: %7.2f%%  Peak: %7.2f%%\n", curCpu, avgCpu, pkCpu);
    printf("=================================================================\n\n");
}

/* Runs for the whole process lifetime (not just while a call is active), so
 * it also captures idle baseline usage between calls. */
static void *resourceMonitorThread(void *arg)
{
    (void)(arg);
    printf("[Device] Resource monitor thread started (interval=%ds)\n", RESOURCE_MONITOR_INTERVAL_SEC);
    uint32_t tick = 0;
    while (!gCtx.terminate)
    {
        monitorUpdateMemoryStats();
        monitorUpdateCpuStats();
        if (tick++ % RESOURCE_PRINT_EVERY == 0)
        {
            monitorPrintResourceStatus();
        }
        sleep(RESOURCE_MONITOR_INTERVAL_SEC);
    }
    printf("[Device] Resource monitor thread stopped\n");
    return NULL;
}

/* ---------------------------------------------------------------------- */
/* Tiny JSON helpers (purpose-built for this fixed protocol shape)         */
/* ---------------------------------------------------------------------- */

static const char *jsonSkipWs(const char *p)
{
    while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
    {
        p++;
    }
    return p;
}

/* Locates "fieldName": and returns a pointer to the first non-ws char of
 * the value, or NULL if the field isn't present. */
static const char *jsonFindValue(const char *pJson, const char *pField)
{
    char needle[MAX_ID_LEN + 4];
    const char *p;

    snprintf(needle, sizeof(needle), "\"%s\"", pField);
    p = strstr(pJson, needle);
    if (p == NULL)
    {
        return NULL;
    }
    p += strlen(needle);
    p = jsonSkipWs(p);
    if (*p != ':')
    {
        return NULL;
    }
    p++;
    return jsonSkipWs(p);
}

/* Extracts a plain string value (assumes no embedded quotes/backslashes,
 * true for our own control fields: command, callId, userId, method,
 * candidate lines). */
static uint32_t jsonExtractString(const char *pJson, const char *pField, char *pOut, uint32_t outSize)
{
    const char *p = jsonFindValue(pJson, pField);
    uint32_t i = 0;

    if (p == NULL || *p != '"')
    {
        return 0;
    }
    p++;
    while (*p != '\0' && *p != '"' && i + 1 < outSize)
    {
        pOut[i++] = *p++;
    }
    pOut[i] = '\0';
    return (*p == '"');
}

/* Extracts a nested {...} object as raw JSON text (naive, non-string-aware
 * brace counting - safe here because SDP/ICE-candidate string values never
 * contain literal '{' or '}'). */
static uint32_t jsonExtractObject(const char *pJson, const char *pField, char *pOut, uint32_t outSize)
{
    const char *p = jsonFindValue(pJson, pField);
    int32_t depth = 0;
    uint32_t i = 0;

    if (p == NULL || *p != '{')
    {
        return 0;
    }

    do
    {
        if (*p == '{')
        {
            depth++;
        }
        else if (*p == '}')
        {
            depth--;
        }
        if (i + 1 < outSize)
        {
            pOut[i++] = *p;
        }
        p++;
    } while (*p != '\0' && depth > 0);

    pOut[i] = '\0';
    return (depth == 0);
}

static int32_t jsonExtractInt(const char *pJson, const char *pField, int32_t defaultVal)
{
    const char *p = jsonFindValue(pJson, pField);
    if (p == NULL)
    {
        return defaultVal;
    }
    return (int32_t)strtol(p, NULL, 10);
}

/* ---------------------------------------------------------------------- */
/* Outgoing message queue (thread-safe; drained on LWS_CALLBACK_CLIENT_WRITEABLE) */
/* ---------------------------------------------------------------------- */

static void enqueueOutgoing(char *pMessage)
{
    pthread_mutex_lock(&gCtx.outQueueLock);

    uint32_t nextTail = (gCtx.outQueueTail + 1) % MAX_OUTGOING_QUEUE;
    if (nextTail == gCtx.outQueueHead)
    {
        fprintf(stderr, "Outgoing queue full, dropping message\n");
    }
    else
    {
        strncpy(gCtx.outQueue[gCtx.outQueueTail].data, pMessage, MAX_WS_MESSAGE_SIZE - 1);
        gCtx.outQueue[gCtx.outQueueTail].len = (uint32_t)strlen(gCtx.outQueue[gCtx.outQueueTail].data);
        gCtx.outQueueTail = nextTail;
    }

    pthread_mutex_unlock(&gCtx.outQueueLock);

    if (gCtx.wsContext != NULL)
    {
        lws_cancel_service(gCtx.wsContext);
    }
}

static uint32_t dequeueOutgoing(OutgoingMessage *pOut)
{
    uint32_t got = 0;
    pthread_mutex_lock(&gCtx.outQueueLock);
    if (gCtx.outQueueHead != gCtx.outQueueTail)
    {
        *pOut = gCtx.outQueue[gCtx.outQueueHead];
        gCtx.outQueueHead = (gCtx.outQueueHead + 1) % MAX_OUTGOING_QUEUE;
        got = 1;
    }
    pthread_mutex_unlock(&gCtx.outQueueLock);
    return got;
}

static uint32_t outgoingQueueHasData(void)
{
    uint32_t has;
    pthread_mutex_lock(&gCtx.outQueueLock);
    has = (gCtx.outQueueHead != gCtx.outQueueTail);
    pthread_mutex_unlock(&gCtx.outQueueLock);
    return has;
}

/* ---------------------------------------------------------------------- */
/* Static frame sending (mirrors webRTCClientMaster.c's frame loop)     */
/* ---------------------------------------------------------------------- */

static uint32_t isH264KeyFrame(const uint8_t *pData, uint32_t size)
{
    uint32_t i;
    if (pData == NULL || size < 5)
    {
        return 0;
    }
    for (i = 0; i + 4 < size; i++)
    {
        uint32_t nalStart = 0;
        if (pData[i] == 0x00 && pData[i + 1] == 0x00 && pData[i + 2] == 0x01)
        {
            nalStart = i + 3;
        }
        else if (pData[i] == 0x00 && pData[i + 1] == 0x00 && pData[i + 2] == 0x00 && pData[i + 3] == 0x01)
        {
            nalStart = i + 4;
        }
        else
        {
            continue;
        }
        if (nalStart >= size)
        {
            return 0;
        }
        uint8_t nalType = pData[nalStart] & 0x1F;
        if (nalType == 7 || nalType == 8)
        {
            i = nalStart;
            continue;
        }
        return (nalType == 5);
    }
    return 0;
}

/* filenameFormat is a printf-style pattern for the file name (no directory),
 * with exactly one %llu placeholder for the 1-based frame index, e.g.
 * "frame-%04llu.h264" (video) or "sample-%03llu.opus" (audio) - matching
 * the exact conventions StaticMedia.c uses for each media type. Counting
 * and reading both start at index 1, matching sendVideoPacketsFromDisk()/
 * sendAudioPacketsFromDisk()'s "fileIndex % COUNT + 1" cycling. */
static uint64_t countFrameFiles(char *dir, char *filenameFormat)
{
    uint64_t count = 0;
    uint64_t index = 1;
    char fileName[64];
    char filePath[MAX_PATH_LEN];
    FILE *fp;

    while (index < 100000)
    {
        snprintf(fileName, sizeof(fileName), filenameFormat, (unsigned long long)index);
        snprintf(filePath, MAX_PATH_LEN, "%s/%s", dir, fileName);
        fp = fopen(filePath, "rb");
        if (fp == NULL)
        {
            break;
        }
        fclose(fp);
        count++;
        index++;
    }
    return count;
}

static uint32_t readFrameFile(char *dir, char *filenameFormat, uint64_t index, uint8_t **ppBuffer, uint32_t *pAllocSize, uint32_t *pFrameSize)
{
    char fileName[64];
    char filePath[MAX_PATH_LEN];
    FILE *fp;
    long fileSize;

    snprintf(fileName, sizeof(fileName), filenameFormat, (unsigned long long)index);
    snprintf(filePath, MAX_PATH_LEN, "%s/%s", dir, fileName);
    fp = fopen(filePath, "rb");
    if (fp == NULL)
    {
        return -1;
    }

    fseek(fp, 0, SEEK_END);
    fileSize = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    if (fileSize <= 0)
    {
        fclose(fp);
        return -1;
    }

    if (*pAllocSize < (uint32_t)fileSize)
    {
        uint8_t *pNew = (uint8_t *)realloc(*ppBuffer, (uint32_t)fileSize);
        if (pNew == NULL)
        {
            fclose(fp);
            return -1;
        }
        *ppBuffer = pNew;
        *pAllocSize = (uint32_t)fileSize;
    }

    if (fread(*ppBuffer, 1, (uint32_t)fileSize, fp) != (uint32_t)fileSize)
    {
        fclose(fp);
        return -1;
    }

    fclose(fp);
    *pFrameSize = (uint32_t)fileSize;
    return 0;
}

/* ---------------------------------------------------------------------- */
/* Call slots                                                              */
/* ---------------------------------------------------------------------- */

static uint64_t slotCustom(CallSlot *call)
{
    return (call->gen << 8) | call->index;
}

/* NULL if the slot was re-used (or closed) since the callback was registered */
static CallSlot *slotFromCustom(uint64_t custom)
{
    uint32_t idx = (uint32_t)(custom & 0xFF);
    CallSlot *call;
    if (idx >= gCtx.maxCalls)
    {
        return NULL;
    }
    call = &gCtx.calls[idx];
    return (call->active && call->gen == (custom >> 8)) ? call : NULL;
}

static CallSlot *findCall(const char *callId)
{
    uint32_t i;
    for (i = 0; i < gCtx.maxCalls; i++)
    {
        if (gCtx.calls[i].active && strcmp(gCtx.calls[i].callId, callId) == 0)
        {
            return &gCtx.calls[i];
        }
    }
    return NULL;
}

static CallSlot *allocCall(void)
{
    uint32_t i;
    for (i = 0; i < gCtx.maxCalls; i++)
    {
        if (!gCtx.calls[i].active)
        {
            return &gCtx.calls[i];
        }
    }
    return NULL;
}

/* ---------------------------------------------------------------------- */
/* GStreamer video source (one pipeline per call)                          */
/* ---------------------------------------------------------------------- */

static GstPadProbeReturn bitrateProbeCallback(GstPad *pad, GstPadProbeInfo *info, gpointer userData)
{
    (void)pad;
    BitrateProbeCtx *ctx = (BitrateProbeCtx *)userData;
    GstBuffer *buffer = GST_PAD_PROBE_INFO_BUFFER(info);
    GstClockTime now = gst_util_get_timestamp();

    if (buffer == NULL)
    {
        return GST_PAD_PROBE_OK;
    }
    if (ctx->windowStart == 0)
    {
        ctx->windowStart = now;
    }
    ctx->bytesAccum += gst_buffer_get_size(buffer);
    ctx->frameCount++;
    ctx->totalFrames++;

    if (now - ctx->windowStart >= GST_SECOND)
    {
        double seconds = (double)(now - ctx->windowStart) / (double)GST_SECOND;
        ctx->lastKbps = (ctx->bytesAccum * 8.0 / 1000.0) / seconds;
        ctx->lastFps = ctx->frameCount / seconds;
        ctx->bytesAccum = 0;
        ctx->frameCount = 0;
        ctx->windowStart = now;
    }
    return GST_PAD_PROBE_OK;
}

static GstFlowReturn gstOnNewSampleVideo(GstElement *sink, gpointer data)
{
    CallSlot *call = (CallSlot *)data;
    GstFlowReturn ret = GST_FLOW_OK;
    GstSample *sample;
    GstBuffer *buffer;
    GstMapInfo info;
    uint32_t mapped = 0, isDroppable;
    Frame frame;

    sample = gst_app_sink_pull_sample(GST_APP_SINK(sink));
    if (sample == NULL)
    {
        return GST_FLOW_OK;
    }
    buffer = gst_sample_get_buffer(sample);
    isDroppable = GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_CORRUPTED) || GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DECODE_ONLY) ||
                  (GST_BUFFER_FLAGS(buffer) == GST_BUFFER_FLAG_DISCONT) ||
                  (GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DISCONT) && GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT)) ||
                  !GST_BUFFER_PTS_IS_VALID(buffer);

    if (isDroppable || !GST_CLOCK_TIME_IS_VALID(gst_segment_to_running_time(gst_sample_get_segment(sample), GST_FORMAT_TIME, buffer->pts)) ||
        !gst_buffer_map(buffer, &info, GST_MAP_READ))
    {
        __atomic_fetch_add(&call->framesDropped, 1, __ATOMIC_RELAXED);
        goto CleanUp;
    }
    mapped = 1;

    memset(&frame, 0x00, sizeof(Frame));
    frame.frameData = (uint8_t *)info.data;
    frame.size = (uint32_t)info.size;
    frame.flags = GST_BUFFER_FLAG_IS_SET(buffer, GST_BUFFER_FLAG_DELTA_UNIT) ? FRAME_FLAG_NONE : FRAME_FLAG_KEY_FRAME;
    frame.index = call->videoFrameIndex++;
    frame.presentationTs = call->videoTs;
    frame.decodingTs = call->videoTs;
    call->videoTs += HUNDREDS_OF_NANOS_IN_A_SECOND / (call->fps > 0 ? call->fps : DEFAULT_VIDEO_FPS);

    if (writeFrame(call->videoTransceiver, &frame) != 0)
    {
        /* Non-fatal: SRTP/DTLS may briefly not be ready; keep going. */
        __atomic_fetch_add(&call->writeFailures, 1, __ATOMIC_RELAXED);
        __atomic_fetch_add(&call->framesDropped, 1, __ATOMIC_RELAXED);
    }
    else
    {
        __atomic_fetch_add(&call->framesWritten, 1, __ATOMIC_RELAXED);
    }

CleanUp:
    if (mapped)
    {
        gst_buffer_unmap(buffer, &info);
    }
    gst_sample_unref(sample);
    if (gCtx.terminate || !call->mediaConnected)
    {
        ret = GST_FLOW_EOS;
    }
    return ret;
}

static uint32_t startGstPipeline(CallSlot *call)
{
    GError *gError = NULL;
    GstElement *appsinkVideo;
    char pipeline[TESTSRC_VIDEO_PIPELINE_MAX_CHAR_COUNT];
    int32_t n;

    call->videoFrameIndex = 0;
    call->videoTs = 0;
    call->framesWritten = call->framesDropped = call->writeFailures = 0;
    memset(&call->probe, 0x00, sizeof(call->probe));
    call->probe.label = "video";

    n = snprintf(pipeline, sizeof(pipeline),
                 "videotestsrc pattern=snow is-live=TRUE ! "
                 "queue ! videorate ! videoscale ! videoconvert ! "
                 "video/x-raw,width=%d,height=%d,framerate=%d/1 ! "
                 "clockoverlay halignment=right valignment=top "
                 "time-format=\"%%Y-%%m-%%d %%H:%%M:%%S\" ! "
                 "x264enc name=sampleVideoEncoder bframes=0 speed-preset=veryfast "
                 "bitrate=%d byte-stream=TRUE tune=zerolatency key-int-max=%d ! "
                 "video/x-h264,stream-format=byte-stream,alignment=au,profile=baseline ! "
                 "appsink sync=TRUE emit-signals=TRUE name=appsink-video ",
                 call->width, call->height, call->fps, call->bitrateKbps, call->fps * 2);
    if (n < 0 || n >= (int32_t)sizeof(pipeline))
    {
        fprintf(stderr, "[Device] Failed to build GStreamer pipeline string\n");
        return 1;
    }
    call->gstPipeline = gst_parse_launch(pipeline, &gError);
    if (gError != NULL || call->gstPipeline == NULL)
    {
        fprintf(stderr, "[Device] GStreamer pipeline error: %s\n", gError != NULL ? gError->message : "NULL pipeline");
        g_clear_error(&gError);
        if (call->gstPipeline != NULL)
        {
            gst_object_unref(call->gstPipeline);
            call->gstPipeline = NULL;
        }
        return 1;
    }
    appsinkVideo = gst_bin_get_by_name(GST_BIN(call->gstPipeline), "appsink-video");
    if (appsinkVideo == NULL)
    {
        fprintf(stderr, "[Device] Could not find appsink in GStreamer pipeline\n");
        return 1;
    }
    {
        GstPad *pad = gst_element_get_static_pad(appsinkVideo, "sink");
        if (pad != NULL)
        {
            gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, bitrateProbeCallback, &call->probe, NULL);
            gst_object_unref(pad);
        }
    }
    g_signal_connect(appsinkVideo, "new-sample", G_CALLBACK(gstOnNewSampleVideo), call);
    gst_object_unref(appsinkVideo);

    if (gst_element_set_state(call->gstPipeline, GST_STATE_PLAYING) == GST_STATE_CHANGE_FAILURE)
    {
        fprintf(stderr, "[Device] Failed to set GStreamer pipeline to PLAYING\n");
        return 1;
    }
    printf("[Device] call %u: GStreamer pipeline started (%dx%d @%dfps, %d kbps)\n", call->index, call->width, call->height, call->fps,
           call->bitrateKbps);
    return 0;
}

/* Blocks on the call's pipeline bus until ERROR/EOS (or the call ends), then tears the pipeline down. */
static void *gstBusWatchThread(void *arg)
{
    CallSlot *call = (CallSlot *)arg;
    GstBus *bus;
    GstMessage *msg;
    GError *gError = NULL;
    gchar *gDebug = NULL;

    if (call->gstPipeline == NULL)
    {
        return NULL;
    }
    bus = gst_element_get_bus(call->gstPipeline);
    do
    {
        msg = gst_bus_timed_pop_filtered(bus, 200 * GST_MSECOND, GST_MESSAGE_ERROR | GST_MESSAGE_EOS);
        if (msg != NULL)
        {
            if (GST_MESSAGE_TYPE(msg) == GST_MESSAGE_ERROR)
            {
                gst_message_parse_error(msg, &gError, &gDebug);
                fprintf(stderr, "[Device] call %u: GStreamer error: %s (%s)\n", call->index, gError->message, gDebug != NULL ? gDebug : "");
                g_clear_error(&gError);
                g_free(gDebug);
            }
            gst_message_unref(msg);
            break;
        }
    } while (!gCtx.terminate && call->mediaConnected);

    gst_object_unref(bus);
    gst_element_set_state(call->gstPipeline, GST_STATE_NULL);
    gst_object_unref(call->gstPipeline);
    call->gstPipeline = NULL;
    return NULL;
}

/* ---------------------------------------------------------------------- */
/* Static-file video source (pre-encoded frames, loaded into RAM per call)  */
/* ---------------------------------------------------------------------- */

static void freeStaticFrames(CallSlot *call)
{
    uint32_t i;
    for (i = 0; i < call->staticFrameCount; i++)
    {
        free(call->staticFrames[i].data);
    }
    free(call->staticFrames);
    call->staticFrames = NULL;
    call->staticFrameCount = 0;
}

/* Chooses the frame directory for this call and loads every frame. With --profiles-dir the folder must match
 * the requested width/height/fps/bitrate exactly (they are baked into pre-encoded frames); without it the single
 * --h264-dir clip is used and only the fps pacing follows the client. Returns 0 on success. */
static uint32_t prepareStaticProfile(CallSlot *call)
{
    uint8_t *pBuffer = NULL;
    uint32_t allocSize = 0, frameSize = 0, i;
    uint64_t count, bytes = 0;

    freeStaticFrames(call);
    if (gCtx.profilesRoot[0] != '\0')
    {
        snprintf(call->staticDir, sizeof(call->staticDir), "%s/%dx%d_%dfps_%dkbps", gCtx.profilesRoot, call->width, call->height, call->fps,
                 call->bitrateKbps);
    }
    else
    {
        snprintf(call->staticDir, sizeof(call->staticDir), "%s", gCtx.h264Dir);
    }
    count = countFrameFiles(call->staticDir, "frame-%04llu.h264");
    if (count == 0)
    {
        fprintf(stderr, "[Device][TC02] no frames in %s (profile not generated?)\n", call->staticDir);
        return 1;
    }
    call->staticFrames = (StaticFrame *)calloc((size_t)count, sizeof(StaticFrame));
    if (call->staticFrames == NULL)
    {
        return 1;
    }
    for (i = 0; i < (uint32_t)count; i++)
    {
        if (readFrameFile(call->staticDir, "frame-%04llu.h264", (uint64_t)i + 1, &pBuffer, &allocSize, &frameSize) != 0)
        {
            break;
        }
        call->staticFrames[i].data = (uint8_t *)malloc(frameSize);
        if (call->staticFrames[i].data == NULL)
        {
            break;
        }
        memcpy(call->staticFrames[i].data, pBuffer, frameSize);
        call->staticFrames[i].size = frameSize;
        call->staticFrames[i].isKey = isH264KeyFrame(pBuffer, frameSize);
        call->staticFrameCount = i + 1;
        bytes += frameSize;
    }
    free(pBuffer);
    if (call->staticFrameCount != (uint32_t)count)
    {
        freeStaticFrames(call);
        return 1;
    }
    printf("[Device][TC02] call %u: loaded %u frames from %s (~%.0f kbps at %d fps)\n", call->index, call->staticFrameCount, call->staticDir,
           bytes * 8.0 / 1000.0 / ((double)call->staticFrameCount / call->fps), call->fps);
    return 0;
}

/* Loops the pre-loaded frames at exactly call->fps (absolute-deadline pacing, no drift) and feeds the same
 * counters / probe as the GStreamer path, so DEVICE_STATS looks identical for both sources. */
static void *videoSendThread(void *arg)
{
    CallSlot *call = (CallSlot *)arg;
    Frame frame;
    uint64_t frameIndex = 0, presentationTs = 0, winBytes = 0;
    uint32_t winFrames = 0;
    int32_t fps = call->fps > 0 ? call->fps : DEFAULT_VIDEO_FPS;
    struct timespec start, next, nowTs, winStart;

    call->framesWritten = call->framesDropped = call->writeFailures = 0;
    memset(&call->probe, 0x00, sizeof(call->probe));
    call->probe.label = "video";

    printf("[Device] call %u: video send thread started (%u frames from %s, %d fps)\n", call->index, call->staticFrameCount, call->staticDir, fps);
    clock_gettime(CLOCK_MONOTONIC, &start);
    winStart = start;

    while (!gCtx.terminate && call->mediaConnected && call->staticFrameCount > 0)
    {
        StaticFrame *sf = &call->staticFrames[frameIndex % call->staticFrameCount];
        uint64_t offsetNs;
        double sec;

        memset(&frame, 0x00, sizeof(Frame));
        frame.frameData = sf->data;
        frame.size = sf->size;
        frame.index = (uint32_t)frameIndex;
        frame.flags = sf->isKey ? FRAME_FLAG_KEY_FRAME : FRAME_FLAG_NONE;
        frame.presentationTs = presentationTs;
        frame.decodingTs = presentationTs;
        if (writeFrame(call->videoTransceiver, &frame) != 0)
        {
            __atomic_fetch_add(&call->writeFailures, 1, __ATOMIC_RELAXED);
            __atomic_fetch_add(&call->framesDropped, 1, __ATOMIC_RELAXED);
        }
        else
        {
            __atomic_fetch_add(&call->framesWritten, 1, __ATOMIC_RELAXED);
        }
        call->probe.totalFrames++;
        winBytes += sf->size;
        winFrames++;

        presentationTs += HUNDREDS_OF_NANOS_IN_A_SECOND / fps;
        frameIndex++;

        offsetNs = frameIndex * 1000000000ULL / (uint64_t)fps;
        next.tv_sec = start.tv_sec + (time_t)(offsetNs / 1000000000ULL);
        next.tv_nsec = start.tv_nsec + (long)(offsetNs % 1000000000ULL);
        if (next.tv_nsec >= 1000000000L)
        {
            next.tv_sec++;
            next.tv_nsec -= 1000000000L;
        }
        clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);

        clock_gettime(CLOCK_MONOTONIC, &nowTs);
        sec = (double)(nowTs.tv_sec - winStart.tv_sec) + (double)(nowTs.tv_nsec - winStart.tv_nsec) / 1e9;
        if (sec >= 1.0)
        {
            call->probe.lastKbps = winBytes * 8.0 / 1000.0 / sec;
            call->probe.lastFps = winFrames / sec;
            winBytes = 0;
            winFrames = 0;
            winStart = nowTs;
        }
    }
    printf("[Device] call %u: video send thread stopped\n", call->index);
    return NULL;
}

/* ---------------------------------------------------------------------- */
/* Audio: a synthetic 1 kHz tone in G.711 mu-law (PCMU, 8 kHz, 20 ms frames) */
/* ---------------------------------------------------------------------- */

static uint8_t gPcmuFrame[PCMU_FRAME_BYTES];

static uint8_t linearToMulaw(int16_t pcm)
{
    int32_t sign = (pcm >> 8) & 0x80;
    int32_t magnitude = pcm;
    int32_t exponent = 7, mask, mantissa;

    if (sign)
    {
        magnitude = -magnitude;
    }
    if (magnitude > 32635)
    {
        magnitude = 32635;
    }
    magnitude += 0x84;
    for (mask = 0x4000; (magnitude & mask) == 0 && exponent > 0; exponent--, mask >>= 1)
    {
    }
    mantissa = (magnitude >> (exponent + 3)) & 0x0F;
    return (uint8_t)~(sign | (exponent << 4) | mantissa);
}

/* 1 kHz at 8 kHz sampling is exactly 8 samples per period and a 160-sample frame holds 20 periods,
 * so one pre-computed frame can be sent over and over with no phase glitch. Built with integers only. */
static void initPcmuTone(void)
{
    static const int16_t period[8] = {0, 5657, 8000, 5657, 0, -5657, -8000, -5657}; /* amplitude 8000 (about -12 dBFS) */
    uint32_t i;

    for (i = 0; i < PCMU_FRAME_BYTES; i++)
    {
        gPcmuFrame[i] = linearToMulaw(period[i % 8]);
    }
}

/* Sends one PCMU frame every 20 ms (absolute-deadline pacing, like the video thread) while the call is connected. */
static void *audioSendThread(void *arg)
{
    CallSlot *call = (CallSlot *)arg;
    Frame frame;
    uint64_t frameIndex = 0, presentationTs = 0;
    struct timespec start, next;

    printf("[Device] call %u: audio send thread started (PCMU, %d frames/s)\\n", call->index, AUDIO_FPS);
    clock_gettime(CLOCK_MONOTONIC, &start);

    while (!gCtx.terminate && call->mediaConnected)
    {
        uint64_t offsetNs;

        memset(&frame, 0x00, sizeof(Frame));
        frame.frameData = gPcmuFrame;
        frame.size = PCMU_FRAME_BYTES;
        frame.index = (uint32_t)frameIndex;
        frame.flags = FRAME_FLAG_NONE;
        frame.presentationTs = presentationTs;
        frame.decodingTs = presentationTs;
        if (writeFrame(call->audioTransceiver, &frame) != 0)
        {
            __atomic_fetch_add(&call->audioFramesDropped, 1, __ATOMIC_RELAXED);
        }
        else
        {
            __atomic_fetch_add(&call->audioFramesWritten, 1, __ATOMIC_RELAXED);
        }
        presentationTs += HUNDREDS_OF_NANOS_IN_A_SECOND / AUDIO_FPS;
        frameIndex++;

        offsetNs = frameIndex * 1000000000ULL / AUDIO_FPS;
        next.tv_sec = start.tv_sec + (time_t)(offsetNs / 1000000000ULL);
        next.tv_nsec = start.tv_nsec + (long)(offsetNs % 1000000000ULL);
        if (next.tv_nsec >= 1000000000L)
        {
            next.tv_sec++;
            next.tv_nsec -= 1000000000L;
        }
        clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);
    }
    printf("[Device] call %u: audio send thread stopped\\n", call->index);
    return NULL;
}

/* ---------------------------------------------------------------------- */
/* TC02 stats reporter (one thread per call): once per second, collect the  */
/* process CPU/RAM + this call's encoder/sender counters, print them and    */
/* send them over the client-created data channel. CPU/RSS are per PROCESS  */
/* (all concurrent calls share them); activeCalls tells the client how many */
/* streams that figure covers.                                              */
/* ---------------------------------------------------------------------- */

static void *tc02StatsThread(void *arg)
{
    CallSlot *call = (CallSlot *)arg;
    uint64_t prevBytes = 0, prevWritten = 0, prevAudioBytes = 0, prevUs = monitorGetTimeUs();
    uint32_t seq = 0, i;

    printf("[Device][TC02] call %u: stats thread started\n", call->index);
    while (!gCtx.terminate && call->mediaConnected)
    {
        RtcStats stats;
        char json[1280];
        uint64_t nowUs, bytesSent = 0, packetsSent = 0, targetBitrate = 0, written, dropped, writeFail;
        uint32_t discarded = 0;
        uint64_t audioBytes = 0, audioDropped = 0;
        double audioKbps = 0.0;
        double dt, sentKbps, sentFps, cpu, cpuAvg, cpuPeak;
        ProcessMemoryInfo mem;
        PRtcDataChannel dc;
        int32_t len;

        for (i = 0; i < 10 && !gCtx.terminate && call->mediaConnected; i++)
        {
            usleep(100000);
        }
        if (gCtx.terminate || !call->mediaConnected)
        {
            break;
        }
        nowUs = monitorGetTimeUs();
        dt = (nowUs - prevUs) / 1000000.0;
        if (dt <= 0.0)
        {
            dt = 1.0;
        }

        memset(&stats, 0x00, sizeof(stats));
        stats.requestedTypeOfStats = RTC_STATS_TYPE_OUTBOUND_RTP;
        if (call->peerConnection != NULL && call->videoTransceiver != NULL &&
            rtcPeerConnectionGetMetrics(call->peerConnection, call->videoTransceiver, &stats) == 0)
        {
            bytesSent = (uint64_t)stats.rtcStatsObject.outboundRtpStreamStats.sent.bytesSent;
            packetsSent = (uint64_t)stats.rtcStatsObject.outboundRtpStreamStats.sent.packetsSent;
            discarded = (uint32_t)stats.rtcStatsObject.outboundRtpStreamStats.packetsDiscardedOnSend;
            targetBitrate = (uint64_t)stats.rtcStatsObject.outboundRtpStreamStats.targetBitrate;
        }
        if (call->audioEnabled && call->peerConnection != NULL && call->audioTransceiver != NULL)
        {
            RtcStats audioStats;
            memset(&audioStats, 0x00, sizeof(audioStats));
            audioStats.requestedTypeOfStats = RTC_STATS_TYPE_OUTBOUND_RTP;
            if (rtcPeerConnectionGetMetrics(call->peerConnection, call->audioTransceiver, &audioStats) == 0)
            {
                audioBytes = (uint64_t)audioStats.rtcStatsObject.outboundRtpStreamStats.sent.bytesSent;
            }
            audioKbps = audioBytes >= prevAudioBytes ? (audioBytes - prevAudioBytes) * 8.0 / 1000.0 / dt : 0.0;
            prevAudioBytes = audioBytes;
            audioDropped = __atomic_load_n(&call->audioFramesDropped, __ATOMIC_RELAXED);
        }
        written = __atomic_load_n(&call->framesWritten, __ATOMIC_RELAXED);
        dropped = __atomic_load_n(&call->framesDropped, __ATOMIC_RELAXED);
        writeFail = __atomic_load_n(&call->writeFailures, __ATOMIC_RELAXED);
        sentKbps = bytesSent >= prevBytes ? (bytesSent - prevBytes) * 8.0 / 1000.0 / dt : 0.0;
        sentFps = (written - prevWritten) / dt;
        prevBytes = bytesSent;
        prevWritten = written;
        prevUs = nowUs;

        pthread_mutex_lock(&gMonitorLock);
        cpu = gCpuMonitor.current_cpu_percent;
        cpuAvg = gCpuMonitor.avg_cpu_percent;
        cpuPeak = gCpuMonitor.peak_cpu_percent;
        mem = gMemMonitor.current;
        pthread_mutex_unlock(&gMonitorLock);

        len = snprintf(json, sizeof(json),
                       "{\"type\":\"DEVICE_STATS\",\"seq\":%u,\"tsMs\":%llu,\"callIdx\":%u,\"activeCalls\":%u,"
                       "\"cpuPct\":%.1f,\"cpuAvgPct\":%.1f,\"cpuPeakPct\":%.1f,\"rssMB\":%.1f,\"vmSizeMB\":%.1f,"
                       "\"cfgKbps\":%d,\"cfgFps\":%d,\"encKbps\":%.1f,\"encFps\":%.1f,\"encFrames\":%llu,"
                       "\"sentKbps\":%.1f,\"sentFps\":%.1f,\"framesWritten\":%llu,\"framesDropped\":%llu,\"writeFailures\":%llu,"
                       "\"packetsSent\":%llu,\"bytesSent\":%llu,\"packetsDiscarded\":%u,\"targetBitrate\":%llu,\"audioKbps\":%.1f,\"audioDropped\":%llu}",
                       seq++, (unsigned long long)(nowUs / 1000), call->index, activeCallCount(), cpu, cpuAvg, cpuPeak,
                       mem.vm_rss_kb / 1024.0, mem.vm_size_kb / 1024.0, call->bitrateKbps, call->fps, call->probe.lastKbps,
                       call->probe.lastFps, (unsigned long long)call->probe.totalFrames, sentKbps, sentFps, (unsigned long long)written,
                       (unsigned long long)dropped, (unsigned long long)writeFail, (unsigned long long)packetsSent,
                       (unsigned long long)bytesSent, discarded, (unsigned long long)targetBitrate, audioKbps, (unsigned long long)audioDropped);

        printf("[Device][TC02][c%u] calls=%u cpu=%.1f%% rss=%.1fMB enc=%.0fkbps/%.1ffps sent=%.0fkbps/%.1ffps dropped=%llu discarded=%u audio=%.0fkbps\n",
               call->index, activeCallCount(), cpu, mem.vm_rss_kb / 1024.0, call->probe.lastKbps, call->probe.lastFps, sentKbps, sentFps,
               (unsigned long long)dropped, discarded, audioKbps);

        pthread_mutex_lock(&gCtx.callLock);
        dc = call->dataChannel;
        pthread_mutex_unlock(&gCtx.callLock);
        if (dc != NULL && len > 0 && len < (int32_t)sizeof(json))
        {
            dataChannelSend(dc, 0, (uint8_t *)json, (uint32_t)len); /* fails until the channel is open; ignored */
        }
    }
    printf("[Device][TC02] call %u: stats thread stopped\n", call->index);
    return NULL;
}

/* ---------------------------------------------------------------------- */
/* PeerConnection callbacks                                                */
/* ---------------------------------------------------------------------- */

static void sendJson(char *pFormat, ...)
{
    char buffer[MAX_WS_MESSAGE_SIZE];
    va_list args;
    va_start(args, pFormat);
    vsnprintf(buffer, sizeof(buffer), pFormat, args);
    va_end(args);
    enqueueOutgoing(buffer);
}

static void onIceCandidateCallback(uint64_t customData, char *candidateStr)
{
    CallSlot *call;

    if (candidateStr == NULL)
    {
        return;
    }
    pthread_mutex_lock(&gCtx.callLock);
    call = slotFromCustom(customData);
    if (call != NULL)
    {
        /* candidateStr is already JSON in RTCIceCandidateInit shape */
        sendJson(
            "{\"callId\":\"%s\",\"msgType\":\"REQUEST\",\"command\":\"P2P_HANDSHAKE\",\"userId\":\"%s\","
            "\"content\":{\"method\":\"ICE_CANDIDATE\",\"content\":%s}}",
            call->callId, call->userId, candidateStr);
    }
    pthread_mutex_unlock(&gCtx.callLock);
}

static void onConnectionStateChangeCallback(uint64_t customData, RTC_PEER_CONNECTION_STATE state)
{
    CallSlot *call = slotFromCustom(customData);

    printf("[Device] call %u: peer connection state -> %d\n", (uint32_t)(customData & 0xFF), state);
    if (call == NULL)
    {
        return; /* stale callback from a previous call that used this slot */
    }

    if (state == RTC_PEER_CONNECTION_STATE_CONNECTED)
    {
        pthread_mutex_lock(&gCtx.callLock);
        if (!call->mediaStarted)
        {
            call->mediaConnected = 1;
            if (gCtx.mediaSourceType == MEDIA_SOURCE_STATIC_FILES)
            {
                pthread_create(&call->videoThread, NULL, videoSendThread, call);
                call->videoThreadStarted = 1;
            }
            else if (startGstPipeline(call) == 0)
            {
                pthread_create(&call->gstBusThread, NULL, gstBusWatchThread, call);
                call->gstBusThreadStarted = 1;
            }
            else
            {
                fprintf(stderr, "[Device] call %u: failed to start GStreamer pipeline\n", call->index);
                call->mediaConnected = 0;
            }
            call->mediaStarted = 1;
            if (call->mediaConnected)
            {
                if (call->audioEnabled && call->audioTransceiver != NULL)
                {
                    pthread_create(&call->audioThread, NULL, audioSendThread, call);
                    call->audioThreadStarted = 1;
                }
                pthread_create(&call->statsThread, NULL, tc02StatsThread, call);
                call->statsThreadStarted = 1;
            }
        }
        pthread_mutex_unlock(&gCtx.callLock);
    }
    else if (state == RTC_PEER_CONNECTION_STATE_FAILED || state == RTC_PEER_CONNECTION_STATE_DISCONNECTED ||
             state == RTC_PEER_CONNECTION_STATE_CLOSED)
    {
        call->mediaConnected = 0;
        if (state == RTC_PEER_CONNECTION_STATE_FAILED || state == RTC_PEER_CONNECTION_STATE_CLOSED)
        {
            call->peerFailed = 1; /* main loop tears the call down (never from inside an SDK callback) */
        }
    }
}

static void onDataChannelCallback(uint64_t customData, PRtcDataChannel pDataChannel)
{
    CallSlot *call;

    pthread_mutex_lock(&gCtx.callLock);
    call = slotFromCustom(customData);
    if (call != NULL)
    {
        printf("[Device] call %u: data channel '%s' received\n", call->index, pDataChannel->name);
        call->dataChannel = pDataChannel; /* used by tc02StatsThread to report DEVICE_STATS */
    }
    pthread_mutex_unlock(&gCtx.callLock);
}

/* ---------------------------------------------------------------------- */
/* Call setup / signaling message handling                                 */
/* ---------------------------------------------------------------------- */

static uint32_t createCallPeerConnection(CallSlot *call)
{
    uint32_t retStatus = 0;
    RtcConfiguration configuration;
    RtcMediaStreamTrack videoTrack;
    RtcMediaStreamTrack audioTrack;
    RtcRtpTransceiverInit transceiverInit;
    uint32_t serverCount = 0;

    memset(&configuration, 0x00, sizeof(configuration));
    /* ICE servers and policy come from the INVITE (see applyInviteIceConfig); empty = not requested. */
    if (call->ice.stunUrl[0] != '\0')
    {
        strncpy(configuration.iceServers[serverCount].urls, call->ice.stunUrl, MAX_ICE_CONFIG_URI_LEN);
        serverCount++;
    }
    if (call->ice.turnUrl[0] != '\0')
    {
        strncpy(configuration.iceServers[serverCount].urls, call->ice.turnUrl, MAX_ICE_CONFIG_URI_LEN);
        strncpy(configuration.iceServers[serverCount].username, call->ice.turnUser, MAX_ICE_CONFIG_CREDENTIAL_LEN);
        strncpy(configuration.iceServers[serverCount].credential, call->ice.turnPass, MAX_ICE_CONFIG_CREDENTIAL_LEN);
        serverCount++;
    }
    (void)serverCount;
    configuration.iceTransportPolicy = strcmp(call->icePolicy, "relay") == 0 ? ICE_TRANSPORT_POLICY_RELAY : ICE_TRANSPORT_POLICY_ALL;
    /* The TURN password is deliberately not logged. */
    printf("[Device][TC02] call %u ICE: policy=%s stun=\"%s\" turn=\"%s\" turnUser=\"%s\"\n", call->index, call->icePolicy, call->ice.stunUrl,
           call->ice.turnUrl, call->ice.turnUser);
    retStatus = createPeerConnection(&configuration, &call->peerConnection);
    if (retStatus != 0)
    {
        goto CleanUp;
    }
    retStatus = peerConnectionOnIceCandidate(call->peerConnection, slotCustom(call), onIceCandidateCallback);
    if (retStatus != 0)
    {
        goto CleanUp;
    }
    retStatus = peerConnectionOnConnectionStateChange(call->peerConnection, slotCustom(call), onConnectionStateChangeCallback);
    if (retStatus != 0)
    {
        goto CleanUp;
    }
    retStatus = peerConnectionOnDataChannel(call->peerConnection, slotCustom(call), onDataChannelCallback);
    if (retStatus != 0)
    {
        goto CleanUp;
    }

    memset(&videoTrack, 0x00, sizeof(RtcMediaStreamTrack));
    videoTrack.kind = MEDIA_STREAM_TRACK_KIND_VIDEO;
    videoTrack.codec = RTC_CODEC_H264_PROFILE_42E01F_LEVEL_ASYMMETRY_ALLOWED_PACKETIZATION_MODE;
    strcpy(videoTrack.streamId, "DeviceStream");
    strcpy(videoTrack.trackId, "DeviceVideoTrack");

    memset(&transceiverInit, 0x00, sizeof(RtcRtpTransceiverInit));
    transceiverInit.direction = RTC_RTP_TRANSCEIVER_DIRECTION_SENDRECV;

    retStatus = addSupportedCodec(call->peerConnection, videoTrack.codec);
    if (retStatus != 0)
    {
        goto CleanUp;
    }
    retStatus = addTransceiver(call->peerConnection, &videoTrack, &transceiverInit, &call->videoTransceiver);
    if (retStatus != 0)
    {
        goto CleanUp;
    }

    /* Audio only when this call's INVITE asked for it; otherwise the answer has no m=audio line. */
    if (call->audioEnabled)
    {
        memset(&audioTrack, 0x00, sizeof(RtcMediaStreamTrack));
        audioTrack.kind = MEDIA_STREAM_TRACK_KIND_AUDIO;
        audioTrack.codec = RTC_CODEC_MULAW;
        strcpy(audioTrack.streamId, "DeviceStream");
        strcpy(audioTrack.trackId, "DeviceAudioTrack");
        retStatus = addSupportedCodec(call->peerConnection, audioTrack.codec);
        if (retStatus != 0)
        {
            goto CleanUp;
        }
        retStatus = addTransceiver(call->peerConnection, &audioTrack, &transceiverInit, &call->audioTransceiver);
    }

CleanUp:
    return retStatus;
}

static int32_t clampInt(int32_t value, int32_t lo, int32_t hi)
{
    return value < lo ? lo : (value > hi ? hi : value);
}

/* Video parameters requested by the client in INVITE content.video; anything missing keeps the CLI default. */
static void applyInviteVideoConfig(CallSlot *call, const char *pJson)
{
    char content[1024];
    char video[512];
    uint32_t fromClient = 0;

    call->width = gCtx.defWidth;
    call->height = gCtx.defHeight;
    call->fps = gCtx.defFps;
    call->bitrateKbps = gCtx.defBitrateKbps;

    if (jsonExtractObject(pJson, "content", content, sizeof(content)) && jsonExtractObject(content, "video", video, sizeof(video)))
    {
        int32_t w = jsonExtractInt(video, "width", 0);
        int32_t h = jsonExtractInt(video, "height", 0);
        int32_t fps = jsonExtractInt(video, "fps", 0);
        int32_t kbps = jsonExtractInt(video, "bitrate", 0);

        if (w > 0 && h > 0)
        {
            call->width = clampInt(w & ~1, 64, 7680); /* even dimensions for I420/x264 */
            call->height = clampInt(h & ~1, 64, 4320);
            fromClient = 1;
        }
        if (fps > 0)
        {
            call->fps = clampInt(fps, 1, 120);
            fromClient = 1;
        }
        if (kbps > 0)
        {
            call->bitrateKbps = clampInt(kbps, 50, 100000);
            fromClient = 1;
        }
    }
    printf("[Device][TC02] call %u video config (%s): %dx%d @%dfps, %d kbps\n", call->index, fromClient ? "from client" : "defaults", call->width,
           call->height, call->fps, call->bitrateKbps);
}

/* ICE config requested by the client in the INVITE: top-level stunUrl, turnUrl, turnUser, turnPass, iceTransportPolicy.
 * A STUN/TURN field that is absent falls back to the built-in default; one that is present but empty means "none". */
static void applyInviteIceConfig(CallSlot *call, const char *pJson)
{
    if (!jsonExtractString(pJson, "iceTransportPolicy", call->icePolicy, sizeof(call->icePolicy)))
    {
        strcpy(call->icePolicy, "all");
    }
    if (!jsonExtractString(pJson, "stunUrl", call->ice.stunUrl, sizeof(call->ice.stunUrl)))
    {
        strcpy(call->ice.stunUrl, DEFAULT_STUN_URL);
    }
    if (!jsonExtractString(pJson, "turnUrl", call->ice.turnUrl, sizeof(call->ice.turnUrl)))
    {
        strcpy(call->ice.turnUrl, DEFAULT_TURN_URL);
        strcpy(call->ice.turnUser, DEFAULT_TURN_USER);
        strcpy(call->ice.turnPass, DEFAULT_TURN_PASS);
    }
    else
    {
        jsonExtractString(pJson, "turnUser", call->ice.turnUser, sizeof(call->ice.turnUser));
        jsonExtractString(pJson, "turnPass", call->ice.turnPass, sizeof(call->ice.turnPass));
    }
}

/* Audio switch requested by the client in INVITE content.audio (JSON true/false). Absent = off (video only). */
static void applyInviteAudioConfig(CallSlot *call, const char *pJson)
{
    char content[1024];
    const char *value = NULL;

    if (jsonExtractObject(pJson, "content", content, sizeof(content)))
    {
        value = jsonFindValue(content, "audio");
    }
    call->audioEnabled = (value != NULL && strncmp(value, "true", 4) == 0) ? 1 : 0;
    printf("[Device][TC02] call %u audio: %s (%s)\n", call->index, call->audioEnabled ? "on, PCMU" : "off", value != NULL ? "from client" : "not requested");
}

static void printPeerConnectionStats(CallSlot *call)
{
    RtcStats stats;

    if (call->peerConnection == NULL)
    {
        return;
    }
    memset(&stats, 0x00, sizeof(stats));
    stats.requestedTypeOfStats = RTC_STATS_TYPE_PEER_CONNECTION;
    if (rtcPeerConnectionGetMetrics(call->peerConnection, NULL, &stats) == 0)
    {
        printf("[Device] call %u peer connection stats: gathering=%llu ms dtls=%llu ms ice=%llu ms\n", call->index,
               (unsigned long long)stats.rtcStatsObject.rtcPeerConnectionStats.candidateGatheringTime,
               (unsigned long long)stats.rtcStatsObject.rtcPeerConnectionStats.dtlsSessionSetupTime,
               (unsigned long long)stats.rtcStatsObject.rtcPeerConnectionStats.iceHolePunchingTime);
    }
}

static void closeCall(CallSlot *call)
{
    pthread_mutex_lock(&gCtx.closeLock);
    pthread_mutex_lock(&gCtx.callLock);

    if (!call->active)
    {
        pthread_mutex_unlock(&gCtx.callLock);
        pthread_mutex_unlock(&gCtx.closeLock);
        return;
    }

    call->mediaConnected = 0;
    if (call->mediaStarted)
    {
        pthread_mutex_unlock(&gCtx.callLock);
        if (call->statsThreadStarted)
        {
            pthread_join(call->statsThread, NULL);
            call->statsThreadStarted = 0;
        }
        if (call->videoThreadStarted)
        {
            pthread_join(call->videoThread, NULL);
            call->videoThreadStarted = 0;
        }
        if (call->audioThreadStarted)
        {
            pthread_join(call->audioThread, NULL);
            call->audioThreadStarted = 0;
        }
        if (call->gstBusThreadStarted)
        {
            pthread_join(call->gstBusThread, NULL);
            call->gstBusThreadStarted = 0;
        }
        pthread_mutex_lock(&gCtx.callLock);
    }

    printf("[Device][TC02] call %u summary: frames written=%llu dropped=%llu writeFailures=%llu\n", call->index,
           (unsigned long long)call->framesWritten, (unsigned long long)call->framesDropped, (unsigned long long)call->writeFailures);
    if (call->audioEnabled)
    {
        printf("[Device][TC02] call %u summary: audio frames written=%llu dropped=%llu\n", call->index,
               (unsigned long long)call->audioFramesWritten, (unsigned long long)call->audioFramesDropped);
    }

    call->dataChannel = NULL; /* owned by the peer connection; freed with it */
    if (call->peerConnection != NULL)
    {
        printPeerConnectionStats(call);
        closePeerConnection(call->peerConnection);
        freePeerConnection(&call->peerConnection);
    }
    freeStaticFrames(call);

    call->active = 0;
    call->peerFailed = 0;
    call->mediaStarted = 0;
    memset(call->callId, 0x00, sizeof(call->callId));
    memset(call->userId, 0x00, sizeof(call->userId));

    pthread_mutex_unlock(&gCtx.callLock);
    pthread_mutex_unlock(&gCtx.closeLock);
    printf("[Device] call %u closed (active calls now %u/%u)\n", call->index, activeCallCount(), gCtx.maxCalls);
}

static void closeAllCalls(void)
{
    uint32_t i;
    for (i = 0; i < gCtx.maxCalls; i++)
    {
        closeCall(&gCtx.calls[i]);
    }
}

static void handleInvite(const char *pJson)
{
    char callId[MAX_ID_LEN];
    char userId[MAX_ID_LEN];
    CallSlot *call;
    uint32_t status;

    if (!jsonExtractString(pJson, "callId", callId, sizeof(callId)) || !jsonExtractString(pJson, "userId", userId, sizeof(userId)))
    {
        fprintf(stderr, "[Device] Malformed INVITE, ignoring\n");
        return;
    }

    pthread_mutex_lock(&gCtx.callLock);
    if (findCall(callId) != NULL)
    {
        pthread_mutex_unlock(&gCtx.callLock);
        fprintf(stderr, "[Device] ignoring duplicate INVITE for active callId=%s\n", callId);
        return;
    }
    call = allocCall();
    if (call == NULL)
    {
        pthread_mutex_unlock(&gCtx.callLock);
        printf("[Device] Busy (%u/%u calls) - rejecting INVITE callId=%s\n", activeCallCount(), gCtx.maxCalls, callId);
        sendJson(
            "{\"callId\":\"%s\",\"msgType\":\"RESPONSE\",\"command\":\"INVITE\",\"userId\":\"%s\","
            "\"responseCode\":486,\"responseMsg\":\"BUSY_HERE\"}",
            callId, userId);
        return;
    }

    {
        uint32_t idx = call->index;
        uint64_t gen = call->gen;
        memset(call, 0x00, sizeof(*call));
        call->index = idx;
        call->gen = gen + 1; /* invalidates callbacks still registered by the slot's previous call */
    }
    strcpy(call->callId, callId);
    strcpy(call->userId, userId);
    call->startTime = time(NULL);
    call->active = 1;
    applyInviteVideoConfig(call, pJson);
    applyInviteIceConfig(call, pJson);
    applyInviteAudioConfig(call, pJson);

    if (gCtx.mediaSourceType == MEDIA_SOURCE_STATIC_FILES && prepareStaticProfile(call) != 0)
    {
        call->active = 0;
        pthread_mutex_unlock(&gCtx.callLock);
        sendJson(
            "{\"callId\":\"%s\",\"msgType\":\"RESPONSE\",\"command\":\"INVITE\",\"userId\":\"%s\","
            "\"responseCode\":404,\"responseMsg\":\"PROFILE_NOT_FOUND\"}",
            callId, userId);
        return;
    }

    status = createCallPeerConnection(call);
    pthread_mutex_unlock(&gCtx.callLock);

    if (status != 0)
    {
        fprintf(stderr, "[Device] call %u: failed to set up peer connection: 0x%08x\n", call->index, status);
        closeCall(call);
        sendJson(
            "{\"callId\":\"%s\",\"msgType\":\"RESPONSE\",\"command\":\"INVITE\",\"userId\":\"%s\","
            "\"responseCode\":500,\"responseMsg\":\"INTERNAL_SERVER_ERROR\"}",
            callId, userId);
        return;
    }

    printf("[Device] call %u accepted: callId=%s userId=%s (active calls=%u/%u)\n", call->index, callId, userId, activeCallCount(), gCtx.maxCalls);
    sendJson(
        "{\"callId\":\"%s\",\"msgType\":\"RESPONSE\",\"command\":\"INVITE\",\"userId\":\"%s\","
        "\"responseCode\":200,\"responseMsg\":\"OK\",\"content\":{\"callType\":\"VIDEO\","
        "\"video\":{\"width\":%d,\"height\":%d,\"fps\":%d,\"bitrate\":%d},\"audio\":%s}}",
        callId, userId, call->width, call->height, call->fps, call->bitrateKbps, call->audioEnabled ? "true" : "false");
}

static void handleOffer(CallSlot *call, const char *pOfferJson)
{
    RtcSessionDescriptionInit offerSdp;
    RtcSessionDescriptionInit answerSdp;
    char answerJson[MAX_WS_MESSAGE_SIZE];
    uint32_t answerJsonLen = sizeof(answerJson);

    memset(&offerSdp, 0x00, sizeof(offerSdp));
    memset(&answerSdp, 0x00, sizeof(answerSdp));

    pthread_mutex_lock(&gCtx.callLock);
    if (!call->active || call->peerConnection == NULL)
    {
        pthread_mutex_unlock(&gCtx.callLock);
        return;
    }
    if (deserializeSessionDescriptionInit((char *)pOfferJson, (uint32_t)strlen(pOfferJson), &offerSdp) != 0 ||
        setRemoteDescription(call->peerConnection, &offerSdp) != 0 || createAnswer(call->peerConnection, &answerSdp) != 0 ||
        setLocalDescription(call->peerConnection, &answerSdp) != 0 || serializeSessionDescriptionInit(&answerSdp, answerJson, &answerJsonLen) != 0)
    {
        fprintf(stderr, "[Device] call %u: failed to process OFFER / build ANSWER\n", call->index);
        pthread_mutex_unlock(&gCtx.callLock);
        return;
    }
    sendJson(
        "{\"callId\":\"%s\",\"msgType\":\"REQUEST\",\"command\":\"P2P_HANDSHAKE\",\"userId\":\"%s\","
        "\"content\":{\"method\":\"ANSWER\",\"content\":%s}}",
        call->callId, call->userId, answerJson);
    pthread_mutex_unlock(&gCtx.callLock);
    printf("[Device] call %u: sent ANSWER\n", call->index);
}

static void handleRemoteIceCandidate(CallSlot *call, const char *pCandidateJson)
{
    char candidate[2048];

    if (!jsonExtractString(pCandidateJson, "candidate", candidate, sizeof(candidate)) || strlen(candidate) == 0)
    {
        return; /* end-of-candidates marker or malformed - ignore */
    }
    pthread_mutex_lock(&gCtx.callLock);
    if (call->active && call->peerConnection != NULL)
    {
        addIceCandidate(call->peerConnection, candidate);
    }
    pthread_mutex_unlock(&gCtx.callLock);
}

static void handleSignalMessage(const char *pJson)
{
    char command[64];
    char type[64];
    char msgCallId[MAX_ID_LEN] = {0};
    char msgUserId[MAX_ID_LEN] = {0};
    CallSlot *call;

    if (jsonExtractString(pJson, "type", type, sizeof(type)) && strcmp(type, "REGISTER_ACK") == 0)
    {
        printf("[Device] Registration acknowledged\n");
        return;
    }
    if (!jsonExtractString(pJson, "command", command, sizeof(command)))
    {
        return;
    }

    if (strcmp(command, "INVITE") == 0)
    {
        handleInvite(pJson);
        return;
    }

    jsonExtractString(pJson, "callId", msgCallId, sizeof(msgCallId));
    jsonExtractString(pJson, "userId", msgUserId, sizeof(msgUserId));
    call = findCall(msgCallId);

    if (strcmp(command, "HANGUP") == 0)
    {
        if (call != NULL)
        {
            closeCall(call);
        }
        else
        {
            printf("[Device] Ignoring HANGUP for callId=%s (no such active call)\n", msgCallId);
        }
        /* The client waits for this before treating the device slot as free. */
        sendJson(
            "{\"callId\":\"%s\",\"msgType\":\"RESPONSE\",\"command\":\"HANGUP\",\"userId\":\"%s\","
            "\"responseCode\":200,\"responseMsg\":\"OK\"}",
            msgCallId, msgUserId);
    }
    else if (strcmp(command, "P2P_HANDSHAKE") == 0 && call != NULL)
    {
        char contentObj[MAX_WS_MESSAGE_SIZE];
        char method[32];
        char innerObj[MAX_WS_MESSAGE_SIZE];

        if (!jsonExtractObject(pJson, "content", contentObj, sizeof(contentObj)) ||
            !jsonExtractString(contentObj, "method", method, sizeof(method)) ||
            !jsonExtractObject(contentObj, "content", innerObj, sizeof(innerObj)))
        {
            return;
        }
        if (strcmp(method, "OFFER") == 0)
        {
            handleOffer(call, innerObj);
        }
        else if (strcmp(method, "ICE_CANDIDATE") == 0)
        {
            handleRemoteIceCandidate(call, innerObj);
        }
    }
}

/* ---------------------------------------------------------------------- */
/* libwebsockets client                                                    */
/* ---------------------------------------------------------------------- */

static char gRecvBuffer[MAX_WS_MESSAGE_SIZE];
static uint32_t gRecvLen = 0;

static int32_t lwsCallback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, uint32_t len)
{
    (void)(user);

    switch (reason)
    {
    case LWS_CALLBACK_CLIENT_ESTABLISHED:
    {
        printf("[Device] WebSocket connected, registering...\n");
        gCtx.wsConnected = 1;
        char reg[256];
        snprintf(reg, sizeof(reg), "{\"type\":\"REGISTER\",\"clientType\":\"device\",\"clientId\":\"%s\"}", gCtx.deviceId);
        enqueueOutgoing(reg);
        break;
    }

    case LWS_CALLBACK_CLIENT_RECEIVE:
    {
        if (gRecvLen + len < sizeof(gRecvBuffer))
        {
            memcpy(gRecvBuffer + gRecvLen, in, len);
            gRecvLen += (uint32_t)len;
        }
        if (lws_is_final_fragment(wsi))
        {
            gRecvBuffer[gRecvLen] = '\0';
            handleSignalMessage(gRecvBuffer);
            gRecvLen = 0;
        }
        break;
    }

    case LWS_CALLBACK_CLIENT_WRITEABLE:
    {
        OutgoingMessage msg;
        if (dequeueOutgoing(&msg))
        {
            uint8_t buf[LWS_PRE + MAX_WS_MESSAGE_SIZE];
            memcpy(buf + LWS_PRE, msg.data, msg.len);
            lws_write(wsi, buf + LWS_PRE, msg.len, LWS_WRITE_TEXT);
            if (outgoingQueueHasData())
            {
                lws_callback_on_writable(wsi);
            }
        }
        break;
    }

    case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
        fprintf(stderr, "[Device] WebSocket connection error: %s\n", in != NULL ? (char *)in : "unknown");
        gCtx.wsConnected = 0;
        break;

    case LWS_CALLBACK_CLOSED:
    case LWS_CALLBACK_CLIENT_CLOSED:
        printf("[Device] WebSocket closed\n");
        gCtx.wsConnected = 0;
        break;

    case LWS_CALLBACK_EVENT_WAIT_CANCELLED:
        /* Woken up by enqueueOutgoing() from another thread */
        if (gCtx.wsi != NULL && outgoingQueueHasData())
        {
            lws_callback_on_writable(gCtx.wsi);
        }
        break;

    default:
        break;
    }

    return 0;
}

static struct lws_protocols gProtocols[] = {
    {"device-signaling", lwsCallback, 0, MAX_WS_MESSAGE_SIZE, 0, NULL, 0},
    LWS_PROTOCOL_LIST_TERM,
};

static void *wsServiceThread(void *arg)
{
    (void)(arg);
    struct lws_context_creation_info info;
    struct lws_client_connect_info ccinfo;

    memset(&info, 0x00, sizeof(info));
    info.port = CONTEXT_PORT_NO_LISTEN;
    info.protocols = gProtocols;
    info.gid = -1;
    info.uid = -1;

    gCtx.wsContext = lws_create_context(&info);
    if (gCtx.wsContext == NULL)
    {
        fprintf(stderr, "[Device] Failed to create lws context\n");
        return NULL;
    }

    memset(&ccinfo, 0x00, sizeof(ccinfo));
    ccinfo.context = gCtx.wsContext;
    ccinfo.address = gCtx.signalingHost;
    ccinfo.port = gCtx.signalingPort;
    ccinfo.path = "/ws";
    ccinfo.host = gCtx.signalingHost;
    ccinfo.origin = gCtx.signalingHost;
    ccinfo.ssl_connection = 0;

    gCtx.wsi = lws_client_connect_via_info(&ccinfo);
    if (gCtx.wsi == NULL)
    {
        fprintf(stderr, "[Device] Failed to initiate WebSocket connection to %s:%d\n", gCtx.signalingHost, gCtx.signalingPort);
        return NULL;
    }

    while (!gCtx.terminate)
    {
        lws_service(gCtx.wsContext, 50);
    }

    lws_context_destroy(gCtx.wsContext);
    return NULL;
}

/* ---------------------------------------------------------------------- */
/* main                                                                     */
/* ---------------------------------------------------------------------- */

static void printUsage(const char *pProgName)
{
    fprintf(stderr,
            "Usage: %s [deviceId] [signalingHost] [signalingPort] [mediaSource] [options]\n"
            "  deviceId       device id to register as (default: device-1)\n"
            "  signalingHost  signaling server host (default: localhost)\n"
            "  signalingPort  signaling server port (default: 8080)\n"
            "  mediaSource    'file' (default) or 'testsrc' (GStreamer videotestsrc)\n"
            "\n"
            "Options (apply to both media sources; unset values keep the default):\n"
            "  --h264-dir=DIR     dir of frame-NNNN.h264 files. Only used when mediaSource=file.\n"
            "                     (default: ./h264SampleFrames)\n"
            "  --fps=N            video frame rate. file: paces frame sending. testsrc: pipeline framerate.\n"
            "                     (default: %d)\n"
            "  --bitrate=N        video bitrate in kbps. Only affects testsrc; ignored (and inert) for file,\n"
            "                     since those sample frames are already encoded. (default: %d)\n"
            "  --resolution=WxH   video resolution, e.g. 1280x720. Only affects testsrc; ignored for file.\n"
            "                     (default: %dx%d)\n"
            "  --max-calls=N      max concurrent calls / parallel streams (default: 8, max: 32). Extra INVITEs get 486.\n"
            "  --profiles-dir=DIR TC02 static mode: DIR/<W>x<H>_<FPS>fps_<KBPS>kbps/frame-NNNN.h264 chosen from the\n"
            "                     client's requested video config (implies mediaSource=file; unknown profile -> 404).\n"
            "  --call-watchdog=S  force-close a call that lasts longer than S seconds without HANGUP\n"
            "                     (default: 900, 0 = disabled). Video params normally come from the client's INVITE.\n"
            "\n"
            "STUN/TURN, ICE transport policy and audio on/off are not options: each call takes them from its INVITE.\n",
            pProgName, DEFAULT_VIDEO_FPS, DEFAULT_VIDEO_BITRATE_KBPS, DEFAULT_VIDEO_WIDTH, DEFAULT_VIDEO_HEIGHT);
}

/* Parses positional args (deviceId, signalingHost, signalingPort, mediaSource,
 * in that order) plus --h264-dir=/--fps=/--bitrate=/--resolution= flags,
 * which may appear anywhere on the command line and
 * apply regardless of mediaSource (see printUsage() above for exactly how
 * each is used). Populates gCtx directly; invalid values fall back to
 * defaults with a warning rather than aborting. */
static void parseArgs(int32_t argc, char *argv[])
{
    int32_t positionalIndex = 0;
    int32_t i;

    strcpy(gCtx.deviceId, "device-1");
    strcpy(gCtx.signalingHost, "localhost");
    gCtx.signalingPort = 8080;
    strcpy(gCtx.h264Dir, "./h264SampleFrames");
    gCtx.mediaSourceType = MEDIA_SOURCE_GST_TEST; /* TC02: GStreamer is the default source */
    gCtx.callWatchdogSec = 900;
    gCtx.maxCalls = DEFAULT_MAX_CALLS;
    gCtx.videoWidth = DEFAULT_VIDEO_WIDTH;
    gCtx.videoHeight = DEFAULT_VIDEO_HEIGHT;
    gCtx.videoFps = DEFAULT_VIDEO_FPS;
    gCtx.videoBitrateKbps = DEFAULT_VIDEO_BITRATE_KBPS;

    for (i = 1; i < argc; i++)
    {
        char *pArg = argv[i];

        if (strcmp(pArg, "-h") == 0 || strcmp(pArg, "--help") == 0)
        {
            printUsage(argv[0]);
            exit(EXIT_SUCCESS);
        }
        else if (strncmp(pArg, "--h264-dir=", 11) == 0)
        {
            strncpy(gCtx.h264Dir, pArg + 11, MAX_PATH_LEN - 1);
        }
        else if (strncmp(pArg, "--fps=", 6) == 0)
        {
            gCtx.videoFps = atoi(pArg + 6);
            if (gCtx.videoFps <= 0)
            {
                fprintf(stderr, "[Device] Invalid --fps value '%s', using default %d\n", pArg + 6, DEFAULT_VIDEO_FPS);
                gCtx.videoFps = DEFAULT_VIDEO_FPS;
            }
        }
        else if (strncmp(pArg, "--bitrate=", 10) == 0)
        {
            gCtx.videoBitrateKbps = atoi(pArg + 10);
            if (gCtx.videoBitrateKbps <= 0)
            {
                fprintf(stderr, "[Device] Invalid --bitrate value '%s', using default %d\n", pArg + 10, DEFAULT_VIDEO_BITRATE_KBPS);
                gCtx.videoBitrateKbps = DEFAULT_VIDEO_BITRATE_KBPS;
            }
        }
        else if (strncmp(pArg, "--resolution=", 13) == 0)
        {
            int32_t w = 0, h = 0;
            if (sscanf(pArg + 13, "%dx%d", &w, &h) != 2 || w <= 0 || h <= 0)
            {
                fprintf(stderr, "[Device] Invalid --resolution value '%s' (expected WxH), using default %dx%d\n", pArg + 13,
                        DEFAULT_VIDEO_WIDTH, DEFAULT_VIDEO_HEIGHT);
            }
            else
            {
                gCtx.videoWidth = w;
                gCtx.videoHeight = h;
            }
        }
        else if (strncmp(pArg, "--max-calls=", 12) == 0)
        {
            gCtx.maxCalls = (uint32_t)atoi(pArg + 12);
        }
        else if (strncmp(pArg, "--profiles-dir=", 15) == 0)
        {
            strncpy(gCtx.profilesRoot, pArg + 15, MAX_PATH_LEN - 1);
        }
        else if (strncmp(pArg, "--call-watchdog=", 16) == 0)
        {
            gCtx.callWatchdogSec = atoi(pArg + 16);
        }
        else if (strncmp(pArg, "--", 2) == 0)
        {
            fprintf(stderr, "[Device] Unrecognized option '%s', ignoring\n", pArg);
        }
        else
        {
            switch (positionalIndex)
            {
            case 0:
                strncpy(gCtx.deviceId, pArg, MAX_ID_LEN - 1);
                break;
            case 1:
                strncpy(gCtx.signalingHost, pArg, MAX_ID_LEN - 1);
                break;
            case 2:
                gCtx.signalingPort = atoi(pArg);
                break;
            case 3:
                if (strcmp(pArg, "testsrc") == 0)
                {
                    gCtx.mediaSourceType = MEDIA_SOURCE_GST_TEST;
                }
                else if (strcmp(pArg, "file") != 0)
                {
                    fprintf(stderr, "[Device] Unrecognized media source '%s', defaulting to static files\n", pArg);
                }
                break;
            default:
                fprintf(stderr, "[Device] Ignoring unexpected extra argument '%s'\n", pArg);
                break;
            }
            positionalIndex++;
        }
    }
}

static void sigintHandler(int32_t sig)
{
    (void)(sig);
    gCtx.terminate = 1;
    if (gCtx.wsContext != NULL)
    {
        lws_cancel_service(gCtx.wsContext);
    }
}

int32_t main(int32_t argc, char *argv[])
{
    pthread_t wsThread;
    uint32_t status;

    memset(&gCtx, 0x00, sizeof(gCtx));
    pthread_mutex_init(&gCtx.outQueueLock, NULL);
    pthread_mutex_init(&gCtx.callLock, NULL);
    pthread_mutex_init(&gCtx.closeLock, NULL);

    parseArgs(argc, argv);
    gCtx.defWidth = gCtx.videoWidth;
    gCtx.defHeight = gCtx.videoHeight;
    gCtx.defFps = gCtx.videoFps;
    gCtx.defBitrateKbps = gCtx.videoBitrateKbps;
    if (gCtx.maxCalls < 1)
    {
        gCtx.maxCalls = 1;
    }
    if (gCtx.maxCalls > MAX_CALLS_LIMIT)
    {
        gCtx.maxCalls = MAX_CALLS_LIMIT;
    }
    for (uint32_t i = 0; i < MAX_CALLS_LIMIT; i++)
    {
        gCtx.calls[i].index = i;
    }
    initPcmuTone();
    if (gCtx.profilesRoot[0] != '\0')
    {
        gCtx.mediaSourceType = MEDIA_SOURCE_STATIC_FILES;
    }
    else if (gCtx.mediaSourceType == MEDIA_SOURCE_STATIC_FILES)
    {
        fprintf(stderr, "[Device][TC02] WARNING: mediaSource=file without --profiles-dir plays one fixed clip; the client's "
                        "resolution/bitrate are ignored (only fps pacing follows it).\n");
    }

    signal(SIGINT, sigintHandler);

    printf("[Device] deviceId=%s signaling=ws://%s:%d/ws\n", gCtx.deviceId, gCtx.signalingHost, gCtx.signalingPort);
    printf("[Device] maxCalls=%u default video config: %dx%d @%dfps, %d kbps (mediaSource=%s; ICE and audio come from each INVITE)\n", gCtx.maxCalls, gCtx.videoWidth,
           gCtx.videoHeight, gCtx.videoFps, gCtx.videoBitrateKbps, gCtx.mediaSourceType == MEDIA_SOURCE_GST_TEST ? "testsrc" : "file");

    /* Start CPU/RAM monitoring before anything heavy (WebRTC/GStreamer init)
     * so the "initial" baseline reflects the bare process, and keep it
     * running for the process lifetime to cover idle + call time alike. */
    monitorInitMemory();
    monitorInitCpu();
    monitorPrintMemoryReport();
    monitorPrintCpuReport();
    pthread_create(&gCtx.resourceMonitorThread, NULL, resourceMonitorThread, NULL);
    gCtx.resourceMonitorThreadStarted = 1;

    if (gCtx.mediaSourceType == MEDIA_SOURCE_STATIC_FILES)
    {
        gCtx.h264FrameCount = gCtx.profilesRoot[0] ? 1 : countFrameFiles(gCtx.h264Dir, "frame-%04llu.h264");
        if (gCtx.profilesRoot[0])
        {
            printf("[Device][TC02] static profiles root: %s (per-call folder <W>x<H>_<FPS>fps_<KBPS>kbps)\n", gCtx.profilesRoot);
        }
        if (gCtx.h264FrameCount == 0)
        {
            fprintf(stderr,
                    "[Device] WARNING: no static video frames found. Copy the SDK's samples/h264SampleFrames "
                    "next to this binary, or pass a custom path via --h264-dir=.\n");
        }

        if (!gCtx.profilesRoot[0])
        {
            printf("[Device] Found %llu H264 frames in %s\n", (unsigned long long)gCtx.h264FrameCount, gCtx.h264Dir);
        }
    }
    else
    {
        gst_init(&argc, &argv);
    }

    status = initWebRtc();
    if (((status) != 0))
    {
        fprintf(stderr, "initWebRtc failed: 0x%08x\n", status);
        return EXIT_FAILURE;
    }

    pthread_create(&wsThread, NULL, wsServiceThread, NULL);

    printf("[Device] Ready. Waiting for INVITE from user-client.html...\n");
    while (!gCtx.terminate)
    {
        sleep(1);
        for (uint32_t i = 0; i < gCtx.maxCalls; i++)
        {
            CallSlot *call = &gCtx.calls[i];
            if (call->active && call->peerFailed)
            {
                printf("[Device] call %u: peer connection FAILED/CLOSED without HANGUP, closing call\n", i);
                closeCall(call);
            }
            // else if (call->active && gCtx.callWatchdogSec > 0 && (time(NULL) - call->startTime) > gCtx.callWatchdogSec)
            // {
            //     printf("[Device] call %u: watchdog (%ds) expired, closing call\n", i, gCtx.callWatchdogSec);
            //     closeCall(call);
            // }
        }
    }

    printf("[Device] Shutting down...\n");
    closeAllCalls();
    pthread_join(wsThread, NULL);

    if (gCtx.resourceMonitorThreadStarted)
    {
        /* gCtx.terminate is already set by sigintHandler(); just wait for
         * the monitor thread's current sleep() to elapse and it will exit. */
        pthread_join(gCtx.resourceMonitorThread, NULL);
        gCtx.resourceMonitorThreadStarted = 0;
    }

    monitorPrintMemoryReport();
    monitorPrintCpuReport();

    printf("[Device] Exiting\n");
    deinitWebRtc();
    pthread_mutex_destroy(&gCtx.outQueueLock);
    pthread_mutex_destroy(&gCtx.callLock);
    pthread_mutex_destroy(&gCtx.closeLock);

    return EXIT_SUCCESS;
}