/* SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only */
/* Copyright (c) 2025 Brett Sheffield <bacs@librecast.net> */

/* Librecast receiver example */

#include <librecast.h>

int main(void)
{
	char data[BUFSIZ] = {0};
	ssize_t bytes;
	int rc = EXIT_FAILURE;	/* pessimistic, aren't we? */

	/* we start with a Librecast Context (lc_ctx_t) */
	lc_ctx_t *lctx = lc_ctx_new();
	if (!lctx) return rc;

	/* create a Librecast Socket (IPv6) */
	lc_socket_t *sock = lc_socket_new(lctx);
	if (!sock) goto free_ctx;

	/* create a Librecast Channel */
	lc_channel_t *chan = lc_channel_new(lctx, "my very first Librecast channel");

	/* bind the Channel to the Socket */
	lc_channel_bind(sock, chan);

	/* join the Channel or we won't receive any data */
	lc_channel_join(chan);

	/* (optional) enable RaptorQ encoding (RFC6330) */
	lc_channel_coding_set(chan, LC_CODE_FEC_RQ | LC_CODE_FEC_OTI);

	/* recv some multicast data */
	bytes = lc_channel_recv(chan, data, sizeof data, 0);
	if (bytes == -1) goto free_ctx;
	printf("received: '%s' (%zi bytes)\n", data, bytes);

	rc = EXIT_SUCCESS;
free_ctx:
	/* free the Context. This also frees all Sockets, Channels, Routers etc.
	 * created with that Context */
	lc_ctx_free(lctx);
	return rc;
}
