/*
 * Copyright (c) 2013 - Andre Roth <neolynx@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation version 2.1 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 * Or, point your browser to http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 *
 * Described at ETSI EN 300 468 V1.11.1 (2010-04)
 */

#include <libdvbv5/desc_ca.h>
#include <libdvbv5/dvb-fe.h>

#if __GNUC__ >= 9
#pragma GCC diagnostic ignored "-Waddress-of-packed-member"
#endif

int dvb_desc_ca_init(struct dvb_v5_fe_parms *parms, const uint8_t *buf, struct dvb_desc *desc)
{
	struct dvb_desc_ca *d = (struct dvb_desc_ca *) desc;
	const uint8_t *p = buf;
	size_t len, dlen = desc->length;
	size_t start;

	start = offsetof(struct dvb_desc_ca, ca_id);
	len = sizeof(d->ca_id) + sizeof(d->bitfield1);

	if (dlen < len) {
		dvb_logwarn("CA descriptor is too short wrong: expected %zu, received %zu",
			    len, dlen);
		return -1;
	}
	memcpy(((uint8_t *) d) + start, buf, len);
	p += len;
	bswap16(d->ca_id);
	bswap16(d->bitfield1);

	len = dlen - len;
	if (len) {
		d->privdata = malloc(len);
		if (!d->privdata)
			return -1;
		d->privdata_len = len;
		memcpy(d->privdata, p, len);
	} else {
		d->privdata = NULL;
		d->privdata_len = 0;
	}
	return 0;
}

void dvb_desc_ca_print(struct dvb_v5_fe_parms *parms, const struct dvb_desc *desc)
{
	const struct dvb_desc_ca *d = (const struct dvb_desc_ca *) desc;
	dvb_loginfo("|           ca_id             0x%04x", d->ca_id);
	dvb_loginfo("|           ca_pid            0x%04x", d->ca_pid);
	dvb_loginfo("|           privdata length   %d", d->privdata_len);
	if (d->privdata)
		dvb_hexdump(parms, "|           privdata          ", d->privdata, d->privdata_len);
}

void dvb_desc_ca_free(struct dvb_desc *desc)
{
	struct dvb_desc_ca *d = (struct dvb_desc_ca *) desc;
	if (d->privdata)
		free(d->privdata);
}

