1 /*
2  * MOC - music on console
3  * Copyright (C) 2005, 2006 Damian Pietras <daper@daper.net>
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 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This code is based on CMUS aac plugin Copyright 2006 dnk <dnk@bjum.net>
11  *
12  */
13 
14 #ifdef HAVE_CONFIG_H
15 # include "config.h"
16 #endif
17 
18 #include <stdio.h>
19 #include <stdint.h>
20 #include <string.h>
21 #include <assert.h>
22 
23 #include <neaacdec.h>
24 #include <id3tag.h>
25 
26 #define DEBUG
27 
28 #include "common.h"
29 #include "decoder.h"
30 #include "log.h"
31 #include "files.h"
32 
33 /* FAAD_MIN_STREAMSIZE == 768, 6 == # of channels */
34 #define BUFFER_SIZE	(FAAD_MIN_STREAMSIZE * 6 * 4)
35 
36 struct aac_data
37 {
38 	struct io_stream *stream;
39 	char rbuf[BUFFER_SIZE];
40 	int rbuf_len;
41 	int rbuf_pos;
42 
43 	int channels;
44 	int sample_rate;
45 
46 	char *overflow_buf;
47 	int overflow_buf_len;
48 
49 	NeAACDecHandle decoder;	/* typedef void * */
50 
51 	int ok; /* was this stream successfully opened? */
52 	struct decoder_error error;
53 
54 	int bitrate;
55 	int avg_bitrate;
56 	int duration;
57 };
58 
buffer_length(const struct aac_data * data)59 static int buffer_length (const struct aac_data *data)
60 {
61 	return data->rbuf_len - data->rbuf_pos;
62 }
63 
buffer_data(struct aac_data * data)64 static void *buffer_data (struct aac_data *data)
65 {
66 	return data->rbuf + data->rbuf_pos;
67 }
68 
buffer_fill(struct aac_data * data)69 static int buffer_fill (struct aac_data *data)
70 {
71 	ssize_t n;
72 
73 	if (data->rbuf_pos > 0) {
74 		data->rbuf_len = buffer_length (data);
75 		memmove (data->rbuf, data->rbuf + data->rbuf_pos, data->rbuf_len);
76 		data->rbuf_pos = 0;
77 	}
78 
79 	if (data->rbuf_len == BUFFER_SIZE)
80 		return 1;
81 
82 	n = io_read (data->stream, data->rbuf + data->rbuf_len, BUFFER_SIZE - data->rbuf_len);
83 	if (n == -1)
84 		return -1;
85 	if (n == 0)
86 		return 0;
87 
88 	data->rbuf_len += n;
89 	return 1;
90 }
91 
buffer_flush(struct aac_data * data)92 static inline void buffer_flush (struct aac_data *data)
93 {
94 	data->rbuf_len = 0;
95 	data->rbuf_pos = 0;
96 }
97 
buffer_consume(struct aac_data * data,int n)98 static inline void buffer_consume (struct aac_data *data, int n)
99 {
100 	assert (n <= buffer_length(data));
101 
102 	data->rbuf_pos += n;
103 }
104 
buffer_fill_min(struct aac_data * data,int len)105 static int buffer_fill_min (struct aac_data *data, int len)
106 {
107 	int rc;
108 
109 	assert (len < BUFFER_SIZE);
110 
111 	while (buffer_length(data) < len) {
112 		rc = buffer_fill (data);
113 		if (rc <= 0)
114 			return rc;
115 	}
116 
117 	return 1;
118 }
119 
120 /* 'data' must point to at least 6 bytes of data */
parse_frame(const unsigned char data[6])121 static int parse_frame (const unsigned char data[6])
122 {
123 	int len;
124 
125 	/* http://wiki.multimedia.cx/index.php?title=ADTS */
126 
127 	/* first 12 bits must be set */
128 	if (data[0] != 0xFF)
129 		return 0;
130 	if ((data[1] & 0xF0) != 0xF0)
131 		return 0;
132 
133 	/* layer is always '00' */
134 	if ((data[1] & 0x06) != 0x00)
135 		return 0;
136 
137 	/* frame length is stored in 13 bits */
138 	len  = data[3] << 11;	/* ..1100000000000 */
139 	len |= data[4] << 3;	/* ..xx11111111xxx */
140 	len |= data[5] >> 5;	/* ..xxxxxxxxxx111 */
141 	len &= 0x1FFF;		/* 13 bits */
142 	return len;
143 }
144 
145 /* scans forward to the next aac frame and makes sure
146  * the entire frame is in the buffer.
147  */
buffer_fill_frame(struct aac_data * data)148 static int buffer_fill_frame(struct aac_data *data)
149 {
150 	unsigned char *datap;
151 	int rc, n, len;
152 	int max = 32768;
153 
154 	while (1) {
155 		/* need at least 6 bytes of data */
156 		rc = buffer_fill_min(data, 6);
157 		if (rc <= 0)
158 			break;
159 
160 		len = buffer_length(data);
161 		datap = buffer_data(data);
162 
163 		/* scan for a frame */
164 		for (n = 0; n < len - 5; n++) {
165 			/* give up after 32KB */
166 			if (max-- == 0) {
167 				logit ("no frame found!");
168 				/* FIXME: set errno? */
169 				return -1;
170 			}
171 
172 			/* see if there's a frame at this location */
173 			rc = parse_frame(datap + n);
174 			if (rc == 0)
175 				continue;
176 
177 			/* found a frame, consume all data up to the frame */
178 			buffer_consume (data, n);
179 
180 			/* rc == frame length */
181 			rc = buffer_fill_min (data, rc);
182 			if (rc <= 0)
183 				goto end;
184 
185 			return 1;
186 		}
187 
188 		/* consume what we used */
189 		buffer_consume (data, n);
190 	}
191 
192 end:
193 	return rc;
194 }
195 
196 /* This should be called with a unique decoder instance as the seeking
197  * it does triggers an FAAD bug which results in distorted audio due to
198  * retained state being corrupted.  (One suspects NeAACDecPostSeekReset()
199  * should resolve the problem but experimentation suggests not and no
200  * documentation exists describing its use.) */
aac_count_time(struct aac_data * data)201 static int aac_count_time (struct aac_data *data)
202 {
203 	NeAACDecFrameInfo frame_info;
204 	int samples = 0, bytes = 0, frames = 0;
205 	off_t file_size;
206 	int16_t *sample_buf;
207 
208 	file_size = io_file_size (data->stream);
209 	if (file_size == -1)
210 		return -1;
211 
212 	if (io_seek(data->stream, file_size / 2, SEEK_SET) == -1)
213 		return -1;
214 	buffer_flush (data);
215 
216 	/* Guess track length by decoding the middle 50 frames which have
217 	 * more than 25% of samples having absolute values greater than 16. */
218 	while (frames < 50) {
219 		if (buffer_fill_frame (data) <= 0)
220 			break;
221 
222 		sample_buf = NeAACDecDecode (data->decoder, &frame_info,
223 		                             buffer_data (data), buffer_length (data));
224 
225 		if (frame_info.error == 0 && frame_info.samples > 0) {
226 			unsigned int ix, zeroes = 0;
227 
228 			for (ix = 0; ix < frame_info.samples; ix += 1) {
229 				if (RANGE(-16, sample_buf[ix], 16))
230 					zeroes += 1;
231 			}
232 
233 			if (zeroes * 4 < frame_info.samples) {
234 				samples += frame_info.samples;
235 				bytes += frame_info.bytesconsumed;
236 				frames += 1;
237 			}
238 		}
239 
240 		if (frame_info.bytesconsumed == 0)
241 			break;
242 
243 		buffer_consume (data, frame_info.bytesconsumed);
244 	}
245 
246 	if (frames == 0)
247 		return -1;
248 
249 	samples /= frames;
250 	samples /= data->channels;
251 	bytes /= frames;
252 
253 	return ((file_size / bytes) * samples) / data->sample_rate;
254 }
255 
aac_open_internal(struct io_stream * stream,const char * fname)256 static void *aac_open_internal (struct io_stream *stream, const char *fname)
257 {
258 	struct aac_data *data;
259 	NeAACDecConfigurationPtr neaac_cfg;
260 	unsigned char channels;
261 	unsigned long sample_rate;
262 	int n;
263 
264 	/* init private struct */
265 	data = (struct aac_data *)xmalloc (sizeof(struct aac_data));
266 	memset (data, 0, sizeof(struct aac_data));
267 	data->ok = 0;
268 	data->decoder = NeAACDecOpen();
269 
270 	/* set decoder config */
271 	neaac_cfg = NeAACDecGetCurrentConfiguration(data->decoder);
272 	neaac_cfg->outputFormat = FAAD_FMT_16BIT;	/* force 16 bit audio */
273 	neaac_cfg->downMatrix = 1;			/* 5.1 -> stereo */
274 	neaac_cfg->dontUpSampleImplicitSBR = 0;		/* upsample, please! */
275 	NeAACDecSetConfiguration(data->decoder, neaac_cfg);
276 
277 	if (stream)
278 		data->stream = stream;
279 	else {
280 		data->stream = io_open (fname, 1);
281 		if (!io_ok(data->stream)) {
282 			decoder_error (&data->error, ERROR_FATAL, 0,
283 					"Can't open AAC file: %s", io_strerror(data->stream));
284 			return data;
285 		}
286 	}
287 
288 	/* find a frame */
289 	if (buffer_fill_frame(data) <= 0) {
290 		decoder_error (&data->error, ERROR_FATAL, 0,
291 				"Not a valid (or unsupported) AAC file");
292 		return data;
293 	}
294 
295 	/* in case of a bug, make sure there is at least some data
296 	 * in the buffer for NeAACDecInit() to work with.
297 	 */
298 	if (buffer_fill_min(data, 256) <= 0) {
299 		decoder_error (&data->error, ERROR_FATAL, 0,
300 				"AAC file/stream too short");
301 		return data;
302 	}
303 
304 	/* init decoder, returns the length of the header (if any) */
305 	channels = (unsigned char)data->channels;
306 	sample_rate = data->sample_rate;
307 	n = NeAACDecInit (data->decoder, buffer_data(data), buffer_length(data),
308 		&sample_rate, &channels);
309 	data->channels = channels;
310 	data->sample_rate = (int)sample_rate;
311 	if (n < 0) {
312 		decoder_error (&data->error, ERROR_FATAL, 0,
313 				"libfaad can't open this stream");
314 		return data;
315 	}
316 
317 	logit ("sample rate %dHz, channels %d", data->sample_rate, data->channels);
318 	if (!data->sample_rate || !data->channels) {
319 		decoder_error (&data->error, ERROR_FATAL, 0,
320 				"Invalid AAC sound parameters");
321 		return data;
322 	}
323 
324 	/* skip the header */
325 	logit ("skipping header (%d bytes)", n);
326 	buffer_consume (data, n);
327 
328 	/*NeAACDecInitDRM(data->decoder, data->sample_rate, data->channels);*/
329 
330 	data->ok = 1;
331 	return data;
332 }
333 
aac_close(void * prv_data)334 static void aac_close (void *prv_data)
335 {
336 	struct aac_data *data = (struct aac_data *)prv_data;
337 
338 	NeAACDecClose (data->decoder);
339 	io_close (data->stream);
340 	decoder_error_clear (&data->error);
341 	free (data);
342 }
343 
344 
aac_open(const char * file)345 static void *aac_open (const char *file)
346 {
347 	struct aac_data *data;
348 
349 	data = aac_open_internal (NULL, file);
350 
351 	if (data->ok) {
352 		int duration = -1;
353 		int avg_bitrate = -1;
354 		off_t file_size;
355 
356 		duration = aac_count_time (data);
357 		file_size = io_file_size (data->stream);
358 		if (duration > 0 && file_size != -1)
359 			avg_bitrate = file_size / duration * 8;
360 		aac_close (data);
361 		data = aac_open_internal (NULL, file);
362 		data->duration = duration;
363 		data->avg_bitrate = avg_bitrate;
364 	}
365 
366 	return data;
367 }
368 
aac_open_stream(struct io_stream * stream)369 static void *aac_open_stream (struct io_stream *stream)
370 {
371 	assert (stream != NULL);
372 
373 	return aac_open_internal (stream, NULL);
374 }
375 
get_tag(struct id3_tag * tag,const char * what)376 static char *get_tag (struct id3_tag *tag, const char *what)
377 {
378 	struct id3_frame *frame;
379 	union id3_field *field;
380 	const id3_ucs4_t *ucs4;
381 	char *comm = NULL;
382 
383 	frame = id3_tag_findframe (tag, what, 0);
384 	if (frame && (field = &frame->fields[1])) {
385 		ucs4 = id3_field_getstrings (field, 0);
386 		if (ucs4)
387 			comm = (char *)id3_ucs4_utf8duplicate (ucs4);
388 	}
389 
390 	return comm;
391 }
392 
393 /* Fill info structure with data from aac comments */
aac_info(const char * file_name,struct file_tags * info,const int tags_sel)394 static void aac_info (const char *file_name,
395 		struct file_tags *info,
396 		const int tags_sel)
397 {
398 	if (tags_sel & TAGS_COMMENTS) {
399 		struct id3_tag *tag;
400 		struct id3_file *id3file;
401 		char *track = NULL;
402 
403 		id3file = id3_file_open (file_name, ID3_FILE_MODE_READONLY);
404 		if (!id3file)
405 			return;
406 		tag = id3_file_tag (id3file);
407 		if (tag) {
408 			info->artist = get_tag (tag, ID3_FRAME_ARTIST);
409 			info->title = get_tag (tag, ID3_FRAME_TITLE);
410 			info->album = get_tag (tag, ID3_FRAME_ALBUM);
411 			track = get_tag (tag, ID3_FRAME_TRACK);
412 
413 			if (track) {
414 				char *end;
415 
416 				info->track = strtol (track, &end, 10);
417 				if (end == track)
418 					info->track = -1;
419 				free (track);
420 			}
421 		}
422 		id3_file_close (id3file);
423 	}
424 
425 	if (tags_sel & TAGS_TIME) {
426 		struct aac_data *data;
427 
428 		data = aac_open_internal (NULL, file_name);
429 
430 		if (data->ok)
431 			info->time = aac_count_time (data);
432 		else
433 			logit ("%s", decoder_error_text (&data->error));
434 
435 		aac_close (data);
436 	}
437 }
438 
aac_seek(void * prv_data ATTR_UNUSED,int sec ATTR_UNUSED)439 static int aac_seek (void *prv_data ATTR_UNUSED, int sec ATTR_UNUSED)
440 {
441 	assert (sec >= 0);
442 
443 	/* AAC will probably never be able to seek.  There is no way of
444 	 * relating the time in the audio to the position in the file
445 	 * short of pre-processing the file at open and building a seek
446 	 * table.  Even then, seeking in the file causes audio glitches
447 	 * (see aac_count_time()). */
448 
449 	return -1;
450 }
451 
452 /* returns -1 on fatal errors
453  * returns -2 on non-fatal errors
454  * 0 on eof
455  * number of bytes put in 'buffer' on success */
decode_one_frame(struct aac_data * data,void * buffer,int count)456 static int decode_one_frame (struct aac_data *data, void *buffer, int count)
457 {
458 	unsigned char *aac_data;
459 	unsigned int aac_data_size;
460 	NeAACDecFrameInfo frame_info;
461 	char *sample_buf;
462 	int bytes, rc;
463 
464 	rc = buffer_fill_frame (data);
465 	if (rc <= 0)
466 		return rc;
467 
468 	aac_data = buffer_data (data);
469 	aac_data_size = buffer_length (data);
470 
471 	/* aac data -> raw pcm */
472 	sample_buf = NeAACDecDecode (data->decoder, &frame_info,
473 	                             aac_data, aac_data_size);
474 
475 	buffer_consume (data, frame_info.bytesconsumed);
476 
477 	if (!sample_buf || frame_info.bytesconsumed <= 0) {
478 		decoder_error (&data->error, ERROR_FATAL, 0, "%s",
479 		               NeAACDecGetErrorMessage (frame_info.error));
480 		return -1;
481 	}
482 
483 	if (frame_info.error != 0) {
484 		decoder_error (&data->error, ERROR_STREAM, 0, "%s",
485 		               NeAACDecGetErrorMessage (frame_info.error));
486 		return -2;
487 	}
488 
489 	if (frame_info.samples <= 0)
490 		return -2;
491 
492 	if (frame_info.channels != (unsigned char)data->channels ||
493 	    frame_info.samplerate != (unsigned long)data->sample_rate) {
494 		decoder_error (&data->error, ERROR_STREAM, 0, "%s",
495 		               "Invalid channel or sample_rate count");
496 		return -2;
497 	}
498 
499 	/* 16-bit samples */
500 	bytes = frame_info.samples * 2;
501 
502 	if (bytes > count) {
503 		/* decoded too much, keep overflow */
504 		data->overflow_buf = sample_buf + count;
505 		data->overflow_buf_len = bytes - count;
506 		memcpy (buffer, sample_buf, count);
507 		return count;
508 	}
509 
510 	memcpy (buffer, sample_buf, bytes);
511 
512 	data->bitrate = frame_info.bytesconsumed * 8 / (bytes / 2.0 /
513 			data->channels / data->sample_rate) / 1000;
514 
515 	return bytes;
516 }
517 
aac_decode(void * prv_data,char * buf,int buf_len,struct sound_params * sound_params)518 static int aac_decode (void *prv_data, char *buf, int buf_len,
519 		struct sound_params *sound_params)
520 {
521 	struct aac_data *data = (struct aac_data *)prv_data;
522 	int rc;
523 
524 	decoder_error_clear (&data->error);
525 
526 	sound_params->channels = data->channels;
527 	sound_params->rate = data->sample_rate;
528 	sound_params->fmt = SFMT_S16 | SFMT_NE;
529 
530 	/* use overflow from previous call (if any) */
531 	if (data->overflow_buf_len) {
532 		int len;
533 
534 		len = MIN(data->overflow_buf_len, buf_len);
535 
536 		memcpy (buf, data->overflow_buf, len);
537 		data->overflow_buf += len;
538 		data->overflow_buf_len -= len;
539 		return len;
540 	}
541 
542 	do {
543 		rc = decode_one_frame (data, buf, buf_len);
544 	} while (rc == -2);
545 
546 	return MAX(rc, 0);
547 }
548 
aac_get_bitrate(void * prv_data)549 static int aac_get_bitrate (void *prv_data)
550 {
551 	struct aac_data *data = (struct aac_data *)prv_data;
552 
553 	return data->bitrate;
554 }
555 
aac_get_avg_bitrate(void * prv_data)556 static int aac_get_avg_bitrate (void *prv_data)
557 {
558 	struct aac_data *data = (struct aac_data *)prv_data;
559 
560 	return data->avg_bitrate / 1000;
561 }
562 
aac_get_duration(void * prv_data)563 static int aac_get_duration (void *prv_data)
564 {
565 	struct aac_data *data = (struct aac_data *)prv_data;
566 
567 	return data->duration;
568 }
569 
aac_get_name(const char * file ATTR_UNUSED,char buf[4])570 static void aac_get_name (const char *file ATTR_UNUSED, char buf[4])
571 {
572 	strcpy (buf, "AAC");
573 }
574 
aac_our_format_ext(const char * ext)575 static int aac_our_format_ext (const char *ext)
576 {
577 	return !strcasecmp (ext, "aac");
578 }
579 
aac_get_error(void * prv_data,struct decoder_error * error)580 static void aac_get_error (void *prv_data, struct decoder_error *error)
581 {
582 	struct aac_data *data = (struct aac_data *)prv_data;
583 
584 	decoder_error_copy (error, &data->error);
585 }
586 
aac_our_mime(const char * mime)587 static int aac_our_mime (const char *mime)
588 {
589 	return !strcasecmp (mime, "audio/aac")
590 		|| !strncasecmp (mime, "audio/aac;", 10)
591 		|| !strcasecmp (mime, "audio/aacp")
592 		|| !strncasecmp (mime, "audio/aacp;", 11);
593 }
594 
595 static struct decoder aac_decoder = {
596 	DECODER_API_VERSION,
597 	NULL,
598 	NULL,
599 	aac_open,
600 	aac_open_stream,
601 	NULL,
602 	aac_close,
603 	aac_decode,
604 	aac_seek,
605 	aac_info,
606 	aac_get_bitrate,
607 	aac_get_duration,
608 	aac_get_error,
609 	aac_our_format_ext,
610 	aac_our_mime,
611 	aac_get_name,
612 	NULL,
613 	NULL,
614 	aac_get_avg_bitrate
615 };
616 
plugin_init()617 struct decoder *plugin_init ()
618 {
619 	return &aac_decoder;
620 }
621