1 /*
2     DABlin - capital DAB experience
3     Copyright (C) 2015-2018 Stefan Pöschel
4 
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9 
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14 
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "dab_decoder.h"
20 
21 // --- MP2Decoder -----------------------------------------------------------------
22 // from ETSI TS 103 466, table 4 (= ISO/IEC 11172-3, table B.2a):
23 const int MP2Decoder::table_nbal_48a[] = {
24 		4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
25 		3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
26 		2, 2, 2, 2
27 };
28 // from ETSI TS 103 466, table 5 (= ISO/IEC 11172-3, table B.2c):
29 const int MP2Decoder::table_nbal_48b[] = {
30 		4, 4,
31 		3, 3, 3, 3, 3, 3
32 };
33 // from ETSI TS 103 466, table 6 (= ISO/IEC 13818-3, table B.1):
34 const int MP2Decoder::table_nbal_24[] = {
35 		4, 4, 4, 4,
36 		3, 3, 3, 3, 3, 3, 3,
37 		2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
38 };
39 const int* MP2Decoder::tables_nbal[] = {
40 		table_nbal_48a,
41 		table_nbal_48b,
42 		table_nbal_24
43 };
44 const int MP2Decoder::sblimits[] = {
45 		sizeof(table_nbal_48a) / sizeof(int),
46 		sizeof(table_nbal_48b) / sizeof(int),
47 		sizeof(table_nbal_24) / sizeof(int),
48 };
49 
50 
MP2Decoder(SubchannelSinkObserver * observer,bool float32)51 MP2Decoder::MP2Decoder(SubchannelSinkObserver* observer, bool float32) : SubchannelSink(observer, "mp2") {
52 	this->float32 = float32;
53 
54 	scf_crc_len = -1;
55 	lsf = false;
56 
57     // Reset DAB+ ACC error
58     observer->ACCFrameError(0);
59 
60 	int mpg_result;
61 
62 	// init
63 	mpg_result = mpg123_init();
64 	if(mpg_result != MPG123_OK)
65 		throw std::runtime_error("MP2Decoder: error while mpg123_init: " + std::string(mpg123_plain_strerror(mpg_result)));
66 
67 	// ensure features
68 	if(!mpg123_feature(MPG123_FEATURE_OUTPUT_32BIT))
69 		throw std::runtime_error("MP2Decoder: no 32bit output support!");
70 	if(!mpg123_feature(MPG123_FEATURE_DECODE_LAYER2))
71 		throw std::runtime_error("MP2Decoder: no Layer II decode support!");
72 
73 	handle = mpg123_new(nullptr, &mpg_result);
74 	if(!handle)
75 		throw std::runtime_error("MP2Decoder: error while mpg123_new: " + std::string(mpg123_plain_strerror(mpg_result)));
76 
77 	fprintf(stderr, "MP2Decoder: using decoder '%s'.\n", mpg123_current_decoder(handle));
78 
79 
80 	// set allowed formats
81 	mpg_result = mpg123_format_none(handle);
82 	if(mpg_result != MPG123_OK)
83 		throw std::runtime_error("MP2Decoder: error while mpg123_format_none: " + std::string(mpg123_plain_strerror(mpg_result)));
84 
85 	mpg_result = mpg123_format(handle, 48000, MPG123_MONO | MPG123_STEREO, float32 ? MPG123_ENC_FLOAT_32 : MPG123_ENC_SIGNED_16);
86 	if(mpg_result != MPG123_OK)
87 		throw std::runtime_error("MP2Decoder: error while mpg123_format #1: " + std::string(mpg123_plain_strerror(mpg_result)));
88 
89 	mpg_result = mpg123_format(handle, 24000, MPG123_MONO | MPG123_STEREO, float32 ? MPG123_ENC_FLOAT_32 : MPG123_ENC_SIGNED_16);
90 	if(mpg_result != MPG123_OK)
91 		throw std::runtime_error("MP2Decoder: error while mpg123_format #2: " + std::string(mpg123_plain_strerror(mpg_result)));
92 
93 	// disable resync limit
94 	mpg_result = mpg123_param(handle, MPG123_RESYNC_LIMIT, -1, 0);
95 	if(mpg_result != MPG123_OK)
96 		throw std::runtime_error("MP2Decoder: error while mpg123_param: " + std::string(mpg123_plain_strerror(mpg_result)));
97 
98 	mpg_result = mpg123_open_feed(handle);
99 	if(mpg_result != MPG123_OK)
100 		throw std::runtime_error("MP2Decoder: error while mpg123_open_feed: " + std::string(mpg123_plain_strerror(mpg_result)));
101 }
102 
~MP2Decoder()103 MP2Decoder::~MP2Decoder() {
104 	if(handle) {
105 		int mpg_result = mpg123_close(handle);
106 		if(mpg_result != MPG123_OK)
107 			fprintf(stderr, "MP2Decoder: error while mpg123_close: %s\n", mpg123_plain_strerror(mpg_result));
108 	}
109 
110 	mpg123_delete(handle);
111 	mpg123_exit();
112 }
113 
Feed(const uint8_t * data,size_t len)114 void MP2Decoder::Feed(const uint8_t *data, size_t len) {
115 	int mpg_result = mpg123_feed(handle, data, len);
116 	if(mpg_result != MPG123_OK)
117 		throw std::runtime_error("MP2Decoder: error while mpg123_feed: " + std::string(mpg123_plain_strerror(mpg_result)));
118 
119 	do {
120 		// go to next frame
121 		mpg_result = mpg123_framebyframe_next(handle);
122 		switch(mpg_result) {
123 		case MPG123_NEED_MORE:
124 			break;	// loop left below
125 		case MPG123_NEW_FORMAT:
126 			ProcessFormat();
127 			// fall through - as MPG123_NEW_FORMAT implies MPG123_OK
128 		case MPG123_OK: {
129 			// forward decoded frame, if applicable
130 			uint8_t *frame_data;
131 			size_t frame_len = DecodeFrame(&frame_data);
132 			if(frame_len)
133 				observer->PutAudio(frame_data, frame_len);
134 			break; }
135 		default:
136 			throw std::runtime_error("MP2Decoder: error while mpg123_framebyframe_next: " + std::string(mpg123_plain_strerror(mpg_result)));
137 		}
138 	} while (mpg_result != MPG123_NEED_MORE);
139 }
140 
DecodeFrame(uint8_t ** data)141 size_t MP2Decoder::DecodeFrame(uint8_t **data) {
142 	int mpg_result;
143 
144 	if(scf_crc_len == -1)
145 		throw std::runtime_error("MP2Decoder: ScF-CRC len not yet set at PAD extraction!");
146 
147 	// derive PAD data from frame
148 	unsigned long header;
149 	uint8_t *body_data;
150 	size_t body_bytes;
151 	mpg_result = mpg123_framedata(handle, &header, &body_data, &body_bytes);
152 	if(mpg_result != MPG123_OK)
153 		throw std::runtime_error("MP2Decoder: error while mpg123_framedata: " + std::string(mpg123_plain_strerror(mpg_result)));
154 
155 	// forwarding the whole frame (except ScF-CRC + F-PAD) as X-PAD, as we don't know the X-PAD len here
156 	observer->ProcessPAD(body_data, body_bytes - FPAD_LEN - scf_crc_len, false, body_data + body_bytes - FPAD_LEN);
157 
158 	// check CRC (MP2's CRC only - not DAB's ScF-CRC)
159 	if(!CheckCRC(header, body_data, body_bytes)) {
160 		observer->AudioError("CRC");
161 		// no PAD reset, as not covered by CRC
162 		return 0;
163 	}
164 
165 	ProcessUntouchedStream(header, body_data, body_bytes);
166 
167 	size_t frame_len;
168 	mpg_result = mpg123_framebyframe_decode(handle, nullptr, data, &frame_len);
169 	if(mpg_result != MPG123_OK)
170 		throw std::runtime_error("MP2Decoder: error while mpg123_framebyframe_decode: " + std::string(mpg123_plain_strerror(mpg_result)));
171 
172 	return frame_len;
173 }
174 
ProcessUntouchedStream(const unsigned long & header,const uint8_t * body_data,size_t body_bytes)175 void MP2Decoder::ProcessUntouchedStream(const unsigned long& header, const uint8_t *body_data, size_t body_bytes) {
176 	std::lock_guard<std::mutex> lock(uscs_mutex);
177 
178 	if(uscs.empty())
179 		return;
180 
181 	// adjust buffer size, if needed
182 	if(frame.size() != body_bytes + 4)
183 		frame.resize(body_bytes + 4);
184 
185 	// reassemble MP2 frame
186 	frame[0] = (header >> 24) & 0xFF;
187 	frame[1] = (header >> 16) & 0xFF;
188 	frame[2] = (header >> 8) & 0xFF;
189 	frame[3] = header & 0xFF;
190 	memcpy(&frame[4], body_data, body_bytes);
191 
192 	ForwardUntouchedStream(&frame[0], frame.size(), lsf ? 48 : 24);
193 }
194 
CheckCRC(const unsigned long & header,const uint8_t * body_data,const size_t & body_bytes)195 bool MP2Decoder::CheckCRC(const unsigned long& header, const uint8_t *body_data, const size_t& body_bytes) {
196 	mpg123_frameinfo info;
197 	int mpg_result = mpg123_info(handle, &info);
198 	if(mpg_result != MPG123_OK)
199 		throw std::runtime_error("MP2Decoder: error while mpg123_info: " + std::string(mpg123_plain_strerror(mpg_result)));
200 
201 	// abort, if no CRC present (though required by DAB)
202 	if(!(info.flags & MPG123_CRC))
203 		return false;
204 
205 	// select matching nbal table
206 	int nch = info.mode == MPG123_M_MONO ? 1 : 2;
207 	int table_index = info.version == MPG123_1_0 ? ((info.bitrate / nch) >= 56 ? 0 : 1) : 2;
208 	const int* table_nbal = tables_nbal[table_index];
209 
210 	// count body bits covered by CRC (= allocation + ScFSI)
211 	BitReader br(body_data + CalcCRC::CRCLen, body_bytes - CalcCRC::CRCLen);
212 	size_t body_crc_len = 0;
213 	int sblimit = sblimits[table_index];
214 	int bound = info.mode == MPG123_M_JOINT ? (info.mode_ext + 1) * 4 : sblimit;
215 	for(int sb = 0; sb < bound; sb++) {
216 		for(int ch = 0; ch < nch; ch++) {
217 			int nbal = table_nbal[sb];
218 			body_crc_len += nbal;
219 
220 			int index;
221 			if(!br.GetBits(index, nbal))
222 				return false;
223 
224 			if(index)
225 				body_crc_len += 2;
226 		}
227 	}
228 	for(int sb = bound; sb < sblimit; sb++) {
229 		int nbal = table_nbal[sb];
230 		body_crc_len += nbal;
231 
232 		int index;
233 		if(!br.GetBits(index, nbal))
234 			return false;
235 
236 		for(int ch = 0; ch < nch; ch++) {
237 			if(index)
238 				body_crc_len += 2;
239 		}
240 	}
241 
242 	// calc CRC
243 	uint16_t crc_stored = (body_data[0] << 8) + body_data[1];
244 	uint16_t crc_calced;
245 	CalcCRC::CalcCRC_CRC16_IBM.Initialize(crc_calced);
246 	CalcCRC::CalcCRC_CRC16_IBM.ProcessByte(crc_calced, (header & 0x0000FF00) >> 8);
247 	CalcCRC::CalcCRC_CRC16_IBM.ProcessByte(crc_calced, header & 0x000000FF);
248 	CalcCRC::CalcCRC_CRC16_IBM.ProcessBits(crc_calced, body_data + CalcCRC::CRCLen, body_crc_len);
249 	CalcCRC::CalcCRC_CRC16_IBM.Finalize(crc_calced);
250 
251 	return crc_stored == crc_calced;
252 }
253 
ProcessFormat()254 void MP2Decoder::ProcessFormat() {
255 	mpg123_frameinfo info;
256 	int mpg_result = mpg123_info(handle, &info);
257 	if(mpg_result != MPG123_OK)
258 		throw std::runtime_error("MP2Decoder: error while mpg123_info: " + std::string(mpg123_plain_strerror(mpg_result)));
259 
260 	scf_crc_len = (info.version == MPG123_1_0 && info.bitrate < (info.mode == MPG123_M_MONO ? 56 : 112)) ? 2 : 4;
261 
262 	// output format
263 	std::string version = "unknown";
264 	switch(info.version) {
265 	case MPG123_1_0:
266 		version = "1.0";
267 		break;
268 	case MPG123_2_0:
269 		version = "2.0";
270 		break;
271 	case MPG123_2_5:
272 		version = "2.5";
273 		break;
274 	}
275 	lsf = info.version != MPG123_1_0;
276 
277 	std::string layer = "unknown";
278 	switch(info.layer) {
279 	case 1:
280 		layer = "I";
281 		break;
282 	case 2:
283 		layer = "II";
284 		break;
285 	case 3:
286 		layer = "III";
287 		break;
288 	}
289 
290 	std::string mode = "unknown";
291 	switch(info.mode) {
292 	case MPG123_M_STEREO:
293 		mode = "Stereo";
294 		break;
295 	case MPG123_M_JOINT:
296 		mode = "Joint Stereo";
297 		break;
298 	case MPG123_M_DUAL:
299 		mode = "Dual Channel";
300 		break;
301 	case MPG123_M_MONO:
302 		mode = "Mono";
303 		break;
304 	}
305 
306 	AUDIO_SERVICE_FORMAT format;
307 	format.codec = "MPEG " + version + " Layer " + layer;
308 	format.samplerate_khz = info.rate / 1000;
309 	format.mode = mode;
310 	format.bitrate_kbps = info.bitrate;
311 	observer->FormatChange(format);
312 
313 	observer->StartAudio(info.rate, info.mode != MPG123_M_MONO ? 2 : 1, float32);
314 }
315