view amrconv/bwe2oa.c @ 608:d4e42ec4a688 default tip

hrutil: new program gsmhr-decode-r
author Mychaela Falconia <falcon@freecalypso.org>
date Fri, 05 Dec 2025 09:01:14 +0000
parents 2f1e91dd552b
children
line wrap: on
line source

/*
 * This program reads a TW-TS-005 hexadecimal file, expects each record to be
 * AMR in BWE format, converts it to OA format, and writes the output into
 * a new TW-TS-005 hex file.
 */

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "../libtest/tw5reader.h"
#include "../libtest/tw5writer.h"
#include "amr_defs.h"

extern const uint8_t pl_total_bytes_oa[9], pl_total_bytes_bwe[9];

main(argc, argv)
	char **argv;
{
	FILE *inf, *outf;
	unsigned lineno;
	uint8_t frm_in[TWTS005_MAX_FRAME], frm_out[MAX_IF1_BYTES + 2];
	unsigned frm_in_len, cmr, ft, expect_len, out_len, n;
	int rc;

	if (argc != 3) {
		fprintf(stderr, "usage: %s amr-bwe.hex amr-oa.hex\n", argv[0]);
		exit(1);
	}
	inf = fopen(argv[1], "r");
	if (!inf) {
		perror(argv[1]);
		exit(1);
	}
	lineno = 0;
	outf = fopen(argv[2], "w");
	if (!outf) {
		perror(argv[2]);
		exit(1);
	}
	for (;;) {
		rc = twts005_read_frame(inf, &lineno, frm_in, &frm_in_len);
		if (rc < 0) {
			fprintf(stderr, "%s line %u: not valid TW-TS-005\n",
				argv[1], lineno);
			exit(1);
		}
		if (!rc)
			break;
		if (frm_in_len == 0) {
			fputs("NULL\n", outf);
			continue;
		}
		if (frm_in_len < 2) {
inv_payload:		fprintf(stderr,
				"%s line %u: payload is not valid AMR BWE\n",
				argv[1], lineno);
			exit(1);
		}
		cmr = frm_in[0] >> 4;
		if (cmr > MR122 && cmr != MODE_NO_DATA)
			goto inv_payload;
		if (frm_in[0] & 0x08)
			goto inv_payload;
		ft = ((frm_in[0] & 0x07) << 1) | ((frm_in[1] & 0x80) >> 7);
		if (ft <= MRDTX)
			expect_len = pl_total_bytes_bwe[ft];
		else if (ft == MODE_NO_DATA)
			expect_len = 2;
		else
			goto inv_payload;
		if (frm_in_len != expect_len)
			goto inv_payload;
		/* With some frame types, the number of padding bits in OA
		 * output will be greater than the number of padding bits in
		 * BWE input.  The easiest way to ensure zero fill in those bits
		 * is to zero the byte just past the input.  Because our frm_in
		 * buffer is sized for TW-TS-005, we have room.
		 */
		frm_in[expect_len] = 0;
		/* proceed to output */
		if (ft != MODE_NO_DATA)
			out_len = pl_total_bytes_oa[ft];
		else
			out_len = 2;
		frm_out[0] = cmr << 4;
		frm_out[1] = (ft << 3) | ((frm_in[1] & 0x40) >> 4);
		for (n = 2; n < out_len; n++)
			frm_out[n] = (frm_in[n-1] << 2) | (frm_in[n] >> 6);
		emit_hex_frame(outf, frm_out, out_len);
	}
	exit(0);
}