view ater8/read_file.c @ 51:db39e8855f3d

ater: implement play-d144
author Mychaela Falconia <falcon@freecalypso.org>
date Wed, 25 Sep 2024 05:53:38 +0000
parents ff94d7fc5891
children
line wrap: on
line source

/*
 * Here we implement the function that reads ETSI *.dec binary files
 * which we've adopted as our TRAU-UL test input format for GSM-HR.
 */

#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "../libhr/tw_gsmhr.h"

#include "read_file.h"

static int validate_frames(const int16_t *buf, unsigned nframes)
{
	unsigned n;
	int rc;
	int16_t expect_taf;

	for (n = 0; n < nframes; n++) {
		rc = gsmhr_check_decoder_params(buf);
		if (rc < 0)
			return rc;
		/* disallow BFI=2 non-ETSI extension */
		if (buf[18] > 1)
			return -1;
		/* enforce TAF matching position */
		if (n % 12 == 11)
			expect_taf = 1;
		else
			expect_taf = 0;
		if (buf[21] != expect_taf)
			return -1;
		buf += GSMHR_NUM_PARAMS_DEC;
	}
	return 0;
}

int read_binary_file(const char *filename, int16_t **bufret, unsigned *size_ret)
{
	int fd, rc;
	struct stat st;
	int16_t *buf;
	unsigned nframes;

	fd = open(filename, O_RDONLY);
	if (fd < 0) {
		perror(filename);
		return -1;
	}
	fstat(fd, &st);
	if (!S_ISREG(st.st_mode)) {
		close(fd);
		fprintf(stderr, "error: %s is not a regular file\n", filename);
		return -1;
	}
	if (!st.st_size) {
		close(fd);
		fprintf(stderr, "error: %s is an empty file\n", filename);
		return -1;
	}
	if (st.st_size % 44) {
		close(fd);
		fprintf(stderr,
			"error: size of %s is not a multiple of 44 bytes\n",
			filename);
		return -1;
	}
	buf = malloc(st.st_size);
	if (!buf) {
		close(fd);
		fprintf(stderr, "unable to malloc buffer for %s\n", filename);
		return -1;
	}
	read(fd, buf, st.st_size);
	close(fd);
	nframes = st.st_size / 44;

	rc = validate_frames(buf, nframes);
	if (rc < 0) {
		free(buf);
		fprintf(stderr,
	"error: %s is not a valid GSM-HR dec file, or has wrong endian\n",
			filename);
		return -1;
	}
	*bufret = buf;
	*size_ret = nframes;
	return 0;
}