shithub: aacenc

Download patch

ref: df60d269323a7eeb1b98de06ede657fc49a8407f
parent: 4fa4bb373f165492ceaa7b741720a1b8edf160d5
author: Sigrid Solveig Haflínudóttir <ftrvxmtrx@gmail.com>
date: Fri Jul 16 11:18:10 EDT 2021

wrap ADTS into PES when -p option passed

--- a/frontend/aacenc.c
+++ b/frontend/aacenc.c
@@ -24,10 +24,40 @@
 #include <bio.h>
 #include <faac.h>
 
+static int
+pesheader(Biobuf *o, int srate, int nfr, int sz)
+{
+	u8int p[] = {
+		0x00, 0x00, 0x01, /* start code */
+		0xc0, /* stream id: audio 0 */
+		0, 0, /* packet length */
+		0x00, /* a bunch of nothing */
+		0x80, /* PTS included */
+		5, /* PTS is 5 bytes */
+		0, 0, 0, 0, 0, /* PTS value */
+	};
+	int plen;
+	uvlong pts;
+
+	plen = sizeof(p)-6 + sz;
+	assert(plen < 65536);
+	p[4] = plen >> 8;
+	p[5] = plen;
+
+	pts = nfr * 90000ULL / srate;
+	p[9] = 1<<5 | (pts>>30)<<1 | 1;
+	p[10] = pts>>22;
+	p[11] = pts>>14 | 1;
+	p[12] = pts>>7;
+	p[13] = pts<<1 | 1;
+
+	return Bwrite(o, p, sizeof(p));
+}
+
 static void
 usage(void)
 {
-	fprint(2, "usage: %s [-r RATE] [-c CHAN] [-q QUANT] [-t low|main|ltp] [-B BITRATE]\n", argv0);
+	fprint(2, "usage: %s [-c CHAN] [-q QUANT] [-r RATE] [-t low|main|ltp] [-B BITRATE]\n", argv0);
 	exits("usage");
 }
 
@@ -34,12 +64,13 @@
 void
 main(int argc, char **argv)
 {
-	int nch, srate, type, brate, sz, n, r, q;
+	int nch, srate, type, brate, sz, n, r, q, pes, frsz;
 	ulong insamples, outsz, insz;
 	faacEncConfigurationPtr fmt;
 	faacEncHandle e;
 	s16int *pcm;
 	u8int *obuf;
+	uvlong nfr;
 	Biobuf out;
 	Biobuf in;
 	char *s;
@@ -48,6 +79,7 @@
 	srate = 44100;
 	nch = 2;
 	type = LOW;
+	pes = 0;
 	q = 0;
 	ARGBEGIN{
 	case 'B':
@@ -62,6 +94,9 @@
 		if((srate = atoi(EARGF(usage()))) < 1)
 			sysfatal("invalid samplerate %d", srate);
 		break;
+	case 'p':
+		pes = 1;
+		break;
 	case 'q':
 		if((q = atoi(EARGF(usage()))) < 1)
 			sysfatal("invalid quantization quality %d", q);
@@ -108,7 +143,8 @@
 	if(!faacEncSetConfiguration(e, fmt))
 		sysfatal("invalid encoder configuration");
 
-	for(;;){
+	frsz = insamples / nch;
+	for(nfr = 0;;){
 		for(n = 0; n == 0 || (n & (sizeof(*pcm)-1)) != 0; n += r){
 			if((r = Bread(&in, pcm+n, insz-n)) <= 0)
 				break;
@@ -117,7 +153,14 @@
 			break;
 		if((sz = faacEncEncode(e, pcm, n/sizeof(*pcm), obuf, outsz)) < 0)
 			sysfatal("faacEncEncode");
-		Bwrite(&out, obuf, sz);
+		if(pes){
+			if(pesheader(&out, srate, nfr, sz) < 0)
+				break;
+			n = n / sizeof(*pcm) / nch;
+			nfr += n < frsz ? frsz : 0;
+		}
+		if(Bwrite(&out, obuf, sz) < 0)
+			break;
 	}
 	Bflush(&out);