From 47fa0ec6ac0901ab5c653a034d61c45de4929887 Mon Sep 17 00:00:00 2001
From: Marten Richter <marten.richter@freenet.de>
Date: Sat, 9 Mar 2013 17:37:59 +0100
Subject: [PATCH] Add mpeg audio header parser

---
 audioomx.cc | 42 ++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 40 insertions(+), 2 deletions(-)

diff --git a/audioomx.cc b/audioomx.cc
index 5e5926b..cf4f564 100644
--- a/audioomx.cc
+++ b/audioomx.cc
@@ -1566,8 +1566,46 @@ unsigned int AudioOMX::AdvanceMpAudioSync(const UCHAR *data,unsigned int size,un
 	if (size<=2) return size; // silly;
 	unsigned int test=0;
 	*framesize=0;
+	//inspired by libav parsing code
 	while (test+1<size) {
-		if (data[test]==0xFF && (data[test+1] &0xe0)==0xe0) return test; // probably FrameSync
+		if (data[test]==0xFF && (data[test+1] &0xe0)==0xe0) {
+			const int sample_rates[4]={44100,48000,32000,0};
+			const short bitrate_tab[2][3][15] = { { { 0, 32, 64, 96, 128, 160,
+					192, 224, 256, 288, 320, 352, 384, 416, 448 }, { 0, 32, 48,
+					56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }, {
+					0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224,
+					256, 320 } }, { { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144,
+					160, 176, 192, 224, 256 }, { 0, 8, 16, 24, 32, 40, 48, 56,
+					64, 80, 96, 112, 128, 144, 160 }, { 0, 8, 16, 24, 32, 40,
+					48, 56, 64, 80, 96, 112, 128, 144, 160 } } };
+			int lsf=0;
+			int mpeg2=0;
+			int layer=4-(data[test+2]&0x03)>>1;
+			int bitrate_index=data[test+2]&0xf0>>4;
+			int padding=(data[test+2]&2)>>1;
+			if (0x10 &  data[test+1]) {
+				lsf=((data[test+1]) &0x8)?0:1;
+				mpeg2=0;
+			} else {
+				lsf=1;
+				mpeg2=1;
+			}
+			int sample_rate=sample_rates[ (data[test+2]&0x0C)>>2]>>(lsf+mpeg2);
+			int frame_size=bitrate_tab[lsf][layer - 1][bitrate_index];
+			if (layer==1) {
+				frame_size=(frame_size*12000)/sample_rate;
+				frame_size=(frame_size+padding)*4;
+			} else if (layer==2) {
+				frame_size=(frame_size*144000)/sample_rate;
+			    frame_size=frame_size+padding;
+			} else {
+				frame_size=(frame_size*144000)/(sample_rate<<lsf);
+				frame_size=frame_size+padding;
+			}
+			*framesize=frame_size;
+
+			return test; // probably FrameSync
+		}
 		test++;
 	}
 	return size;
@@ -1979,7 +2017,7 @@ UINT AudioOMX::DeliverMediaPacket(MediaPacket packet, const UCHAR* buffer,
 					min(haveToCopy,decompress_buffer_size-decompress_buffer_filled));
 			incoming_paket_libav.size = decompress_buffer_filled
 					+min(haveToCopy,decompress_buffer_size-decompress_buffer_filled);
-			//Log::getInstance()->log("Audio", Log::DEBUG,"Use saved audio buffer %d %d %d",packet.type,decompress_buffer_filled,packet.synced);
+			//Log::getInstance()->log("Audio", Log::DEBUG,"Use saved audio buffer %d %d %d",packet.type,decompress_buffer_filled,packet.synched);
 		} else {
 			incoming_paket_libav.data =(uint8_t*) buffer+packet.pos_buffer+*samplepos;
 			incoming_paket_libav.size = haveToCopy;
-- 
2.39.5