Document Replay Gain
[cmus.git] / aac.c
blob6e72f1b57400ea64b2f1de909000facbe08b1dae
1 /*
2 * Copyright 2006 dnk <dnk@bjum.net>
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License as
6 * published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
17 * 02111-1307, USA.
20 #include "ip.h"
21 #include "xmalloc.h"
22 #include "debug.h"
23 #include "id3.h"
24 #include "comment.h"
25 #include "read_wrapper.h"
27 #include <faad.h>
29 #include <errno.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <fcntl.h>
35 /* FAAD_MIN_STREAMSIZE == 768, 6 == # of channels */
36 #define BUFFER_SIZE (FAAD_MIN_STREAMSIZE * 6 * 4)
38 struct aac_private {
39 char rbuf[BUFFER_SIZE];
40 int rbuf_len;
41 int rbuf_pos;
43 unsigned char channels;
44 unsigned long sample_rate;
46 char *overflow_buf;
47 int overflow_buf_len;
49 faacDecHandle decoder; /* typedef void * */
52 static inline int buffer_length(const struct input_plugin_data *ip_data)
54 struct aac_private *priv = ip_data->private;
56 return priv->rbuf_len - priv->rbuf_pos;
59 static inline void *buffer_data(const struct input_plugin_data *ip_data)
61 struct aac_private *priv = ip_data->private;
63 return priv->rbuf + priv->rbuf_pos;
66 static int buffer_fill(struct input_plugin_data *ip_data)
68 struct aac_private *priv = ip_data->private;
69 int32_t n;
71 if (priv->rbuf_pos > 0) {
72 priv->rbuf_len = buffer_length(ip_data);
73 memmove(priv->rbuf, priv->rbuf + priv->rbuf_pos, priv->rbuf_len);
74 priv->rbuf_pos = 0;
77 if (priv->rbuf_len == BUFFER_SIZE)
78 return 1;
80 n = read_wrapper(ip_data, priv->rbuf + priv->rbuf_len, BUFFER_SIZE - priv->rbuf_len);
81 if (n == -1)
82 return -1;
83 if (n == 0)
84 return 0;
86 priv->rbuf_len += n;
87 return 1;
90 static inline void buffer_consume(struct input_plugin_data *ip_data, int n)
92 struct aac_private *priv = ip_data->private;
94 BUG_ON(n > buffer_length(ip_data));
96 priv->rbuf_pos += n;
99 static int buffer_fill_min(struct input_plugin_data *ip_data, int len)
101 int rc;
103 BUG_ON(len > BUFFER_SIZE);
105 while (buffer_length(ip_data) < len) {
106 rc = buffer_fill(ip_data);
107 if (rc <= 0)
108 return rc;
110 return 1;
113 /* 'data' must point to at least 6 bytes of data */
114 static inline int parse_frame(const unsigned char data[6])
116 int len;
118 /* http://www.audiocoding.com/modules/wiki/?page=ADTS */
120 /* first 12 bits must be set */
121 if (data[0] != 0xFF)
122 return 0;
123 if ((data[1] & 0xF0) != 0xF0)
124 return 0;
126 /* layer is always '00' */
127 if ((data[1] & 0x06) != 0x00)
128 return 0;
130 /* frame length is stored in 13 bits */
131 len = data[3] << 11; /* ..1100000000000 */
132 len |= data[4] << 3; /* ..xx11111111xxx */
133 len |= data[5] >> 5; /* ..xxxxxxxxxx111 */
134 len &= 0x1FFF; /* 13 bits */
135 return len;
138 /* scans forward to the next aac frame and makes sure
139 * the entire frame is in the buffer.
141 static int buffer_fill_frame(struct input_plugin_data *ip_data)
143 unsigned char *data;
144 int rc, n, len;
145 int max = 32768;
147 while (1) {
148 /* need at least 6 bytes of data */
149 rc = buffer_fill_min(ip_data, 6);
150 if (rc <= 0)
151 return rc;
153 len = buffer_length(ip_data);
154 data = buffer_data(ip_data);
156 /* scan for a frame */
157 for (n = 0; n < len - 5; n++) {
158 /* give up after 32KB */
159 if (max-- == 0) {
160 d_print("no frame found!\n");
161 /* FIXME: set errno? */
162 return -1;
165 /* see if there's a frame at this location */
166 rc = parse_frame(data + n);
167 if (rc == 0)
168 continue;
170 /* found a frame, consume all data up to the frame */
171 buffer_consume(ip_data, n);
173 /* rc == frame length */
174 rc = buffer_fill_min(ip_data, rc);
175 if (rc <= 0)
176 return rc;
178 return 1;
181 /* consume what we used */
182 buffer_consume(ip_data, n);
184 /* not reached */
187 static int aac_open(struct input_plugin_data *ip_data)
189 struct aac_private *priv;
190 faacDecConfigurationPtr neaac_cfg;
191 int ret, n;
193 /* init private struct */
194 priv = xnew0(struct aac_private, 1);
195 priv->decoder = faacDecOpen();
196 ip_data->private = priv;
198 /* set decoder config */
199 neaac_cfg = faacDecGetCurrentConfiguration(priv->decoder);
200 neaac_cfg->outputFormat = FAAD_FMT_16BIT; /* force 16 bit audio */
201 neaac_cfg->downMatrix = 1; /* 5.1 -> stereo */
202 neaac_cfg->dontUpSampleImplicitSBR = 0; /* upsample, please! */
203 faacDecSetConfiguration(priv->decoder, neaac_cfg);
205 /* find a frame */
206 if (buffer_fill_frame(ip_data) <= 0) {
207 ret = -IP_ERROR_FILE_FORMAT;
208 goto out;
211 /* in case of a bug, make sure there is at least some data
212 * in the buffer for faacDecInit() to work with.
214 if (buffer_fill_min(ip_data, 256) <= 0) {
215 d_print("not enough data\n");
216 ret = -IP_ERROR_FILE_FORMAT;
217 goto out;
220 /* init decoder, returns the length of the header (if any) */
221 n = faacDecInit(priv->decoder, buffer_data(ip_data), buffer_length(ip_data),
222 &priv->sample_rate, &priv->channels);
223 if (n < 0) {
224 d_print("faacDecInit failed\n");
225 ret = -IP_ERROR_FILE_FORMAT;
226 goto out;
229 d_print("sample rate %luhz, channels %u\n", priv->sample_rate, priv->channels);
230 if (!priv->sample_rate || !priv->channels) {
231 ret = -IP_ERROR_FILE_FORMAT;
232 goto out;
235 /* skip the header */
236 d_print("skipping header (%d bytes)\n", n);
238 buffer_consume(ip_data, n);
240 /*faacDecInitDRM(priv->decoder, priv->sample_rate, priv->channels);*/
242 ip_data->sf = sf_rate(priv->sample_rate) | sf_channels(priv->channels) | sf_bits(16) | sf_signed(1);
243 #if defined(WORDS_BIGENDIAN)
244 ip_data->sf |= sf_bigendian(1);
245 #endif
246 return 0;
247 out:
248 faacDecClose(priv->decoder);
249 free(priv);
250 return ret;
253 static int aac_close(struct input_plugin_data *ip_data)
255 struct aac_private *priv = ip_data->private;
257 faacDecClose(priv->decoder);
258 free(priv);
259 ip_data->private = NULL;
260 return 0;
263 /* returns -1 on fatal errors
264 * returns -2 on non-fatal errors
265 * 0 on eof
266 * number of bytes put in 'buffer' on success */
267 static int decode_one_frame(struct input_plugin_data *ip_data, void *buffer, int count)
269 struct aac_private *priv = ip_data->private;
270 unsigned char *aac_data;
271 unsigned int aac_data_size;
272 faacDecFrameInfo frame_info;
273 char *sample_buf;
274 int bytes, rc;
276 rc = buffer_fill_frame(ip_data);
277 if (rc <= 0)
278 return rc;
280 aac_data = buffer_data(ip_data);
281 aac_data_size = buffer_length(ip_data);
283 /* aac data -> raw pcm */
284 sample_buf = faacDecDecode(priv->decoder, &frame_info, aac_data, aac_data_size);
286 buffer_consume(ip_data, frame_info.bytesconsumed);
288 if (!sample_buf || frame_info.bytesconsumed <= 0) {
289 d_print("fatal error: %s\n", faacDecGetErrorMessage(frame_info.error));
290 errno = EINVAL;
291 return -1;
294 if (frame_info.error != 0) {
295 d_print("frame error: %s\n", faacDecGetErrorMessage(frame_info.error));
296 return -2;
299 if (frame_info.samples <= 0)
300 return -2;
302 if (frame_info.channels != priv->channels || frame_info.samplerate != priv->sample_rate) {
303 d_print("invalid channel or sample_rate count\n");
304 return -2;
307 /* 16-bit samples */
308 bytes = frame_info.samples * 2;
310 if (bytes > count) {
311 /* decoded too much, keep overflow */
312 priv->overflow_buf = sample_buf + count;
313 priv->overflow_buf_len = bytes - count;
314 memcpy(buffer, sample_buf, count);
315 return count;
316 } else {
317 memcpy(buffer, sample_buf, bytes);
319 return bytes;
322 static int aac_read(struct input_plugin_data *ip_data, char *buffer, int count)
324 struct aac_private *priv = ip_data->private;
325 int rc;
327 /* use overflow from previous call (if any) */
328 if (priv->overflow_buf_len) {
329 int len = priv->overflow_buf_len;
331 if (len > count)
332 len = count;
334 memcpy(buffer, priv->overflow_buf, len);
335 priv->overflow_buf += len;
336 priv->overflow_buf_len -= len;
337 return len;
340 do {
341 rc = decode_one_frame(ip_data, buffer, count);
342 } while (rc == -2);
343 return rc;
346 static int aac_seek(struct input_plugin_data *ip_data, double offset)
348 return -IP_ERROR_FUNCTION_NOT_SUPPORTED;
351 /* copied from mad.c */
352 static void get_comment(struct keyval *c, int *iptr, struct id3tag *id3, enum id3_key key, const char *key_name)
354 int i = *iptr;
356 c[i].val = id3_get_comment(id3, key);
357 if (c[i].val == NULL)
358 return;
359 c[i].key = xstrdup(key_name);
360 *iptr = i + 1;
363 /* based on read_comments from mad.c */
364 static int aac_read_comments(struct input_plugin_data *ip_data,
365 struct keyval **comments)
367 struct id3tag id3;
368 int rc, fd, i;
370 fd = open(ip_data->filename, O_RDONLY);
371 if (fd == -1)
372 return -1;
374 id3_init(&id3);
375 rc = id3_read_tags(&id3, fd, ID3_V1 | ID3_V2);
376 if (rc == -1) {
377 d_print("error: %s\n", strerror(errno));
378 *comments = xnew0(struct keyval, 1);
379 goto out;
382 *comments = xnew0(struct keyval, NUM_ID3_KEYS + 1);
383 i = 0;
384 get_comment(*comments, &i, &id3, ID3_ARTIST, "artist");
385 get_comment(*comments, &i, &id3, ID3_ALBUM, "album");
386 get_comment(*comments, &i, &id3, ID3_TITLE, "title");
387 get_comment(*comments, &i, &id3, ID3_DATE, "date");
388 get_comment(*comments, &i, &id3, ID3_GENRE, "genre");
389 get_comment(*comments, &i, &id3, ID3_DISC, "discnumber");
390 get_comment(*comments, &i, &id3, ID3_TRACK, "tracknumber");
391 get_comment(*comments, &i, &id3, ID3_ALBUMARTIST, "albumartist");
392 out:
393 close(fd);
394 id3_free(&id3);
395 return 0;
398 static int aac_duration(struct input_plugin_data *ip_data)
400 struct aac_private *priv = ip_data->private;
401 faacDecFrameInfo frame_info;
402 int samples = 0, bytes = 0, frames = 0;
403 off_t file_size;
404 char *sample_buf;
406 file_size = lseek(ip_data->fd, 0, SEEK_END);
407 if (file_size == -1)
408 return -IP_ERROR_FUNCTION_NOT_SUPPORTED;
410 /* guess track length by decoding the first 10 frames */
411 while (frames < 10) {
412 if (buffer_fill_frame(ip_data) <= 0)
413 break;
415 sample_buf = faacDecDecode(priv->decoder, &frame_info,
416 buffer_data(ip_data), buffer_length(ip_data));
417 if (frame_info.error == 0 && frame_info.samples > 0) {
418 samples += frame_info.samples;
419 bytes += frame_info.bytesconsumed;
420 frames++;
422 if (frame_info.bytesconsumed == 0)
423 break;
425 buffer_consume(ip_data, frame_info.bytesconsumed);
428 if (frames == 0)
429 return -IP_ERROR_FUNCTION_NOT_SUPPORTED;
431 samples /= frames;
432 samples /= priv->channels;
433 bytes /= frames;
435 return ((file_size / bytes) * samples) / priv->sample_rate;
438 const struct input_plugin_ops ip_ops = {
439 .open = aac_open,
440 .close = aac_close,
441 .read = aac_read,
442 .seek = aac_seek,
443 .read_comments = aac_read_comments,
444 .duration = aac_duration
447 const char * const ip_extensions[] = { "aac", NULL };
448 const char * const ip_mime_types[] = { "audio/aac", "audio/aacp", NULL };