shithub: mp3dec

Download patch

ref: 03f59ef700028956694e5b5a7c1c29c12ab9bac7
parent: bd30e1069a2783b4e1c7a5538d5ff711d6eca715
author: Sigrid Solveig Haflínudóttir <ftrvxmtrx@gmail.com>
date: Fri Jul 23 06:57:05 EDT 2021

fix non-seekable streams in a better way

--- a/mp3dec.c
+++ b/mp3dec.c
@@ -7,32 +7,31 @@
 
 static int noseek, startsz;
 static uvlong curpos;
-static Biobuf in;
+static Biobufhdr in;
 static uchar inb[MINIMP3_BUF_SIZE];
-static uchar start[2*MINIMP3_BUF_SIZE];
 
 static size_t
 readcb(void *buf, size_t size, void *)
 {
 	int n;
-	if(noseek && curpos < startsz){
-		n = startsz - curpos;
-		n = size < n ? size : n;
-		memmove(buf, start+curpos, n);
-		curpos += n;
-	}else{
-		n = Bread(&in, buf, size);
-	}
-	return n > 0 ? n : 0;
+	return (n = Bread(&in, buf, size)) > 0 ? n : 0;
 }
 
 static int
 seekcb(uint64_t position, void *)
 {
-	if(noseek && curpos <= startsz)
-		curpos = position;
-	else
+	int n;
+
+	if(noseek){
+		if(curpos > position)
+			return -1;
+		for(; position > 0; position -= n, curpos += n){
+			if((n = Bread(&in, inb, MINIMP3_MIN(position, sizeof(inb)))) < 0)
+				return 0;
+		}
+	}else
 		curpos = Bseek(&in, position, 0);
+
 	return 0;
 }
 
@@ -72,8 +71,6 @@
 	noseek = Bseek(&in, 0, 2) < 0;
 	if(!noseek)
 		Bseek(&in, 0, 0);
-	else
-		startsz = Bread(&in, start, sizeof(start));
 	if(mp3dec_ex_open_cb(&dec, &io, MP3D_SEEK_TO_SAMPLE|MP3D_DO_NOT_SCAN) != 0)
 		sysfatal("mp3dec_ex_open_cb");
 	if(seekto != 0.0)
@@ -80,7 +77,7 @@
 		fprint(2, "time: %g\n", (noseek || mp3dec_ex_seek(&dec, seekto*dec.info.channels*dec.info.hz) != 0) ? 0.0 : seekto);
 
 	out = 1;
-	if(dec.info.channels != 2 || dec.info.hz != 44100){
+	if((dec.info.channels != 2 || dec.info.hz != 44100)){
 		pid = -1;
 		if(pipe(pfd) < 0 || (pid = fork()) < 0)
 			sysfatal("%r");
@@ -99,6 +96,7 @@
 
 	while((n = mp3dec_ex_read(&dec, buf, nelem(buf))) > 0)
 		write(out, buf, n*sizeof(buf[0]));
+
 	Bterm(&in);
 	close(out);
 	mp3dec_ex_close(&dec);