afh: Dynamic chunks.
[paraslash.git] / aac_afh.c
1 /*
2  * Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6 /*
7  * based in parts on libfaad, Copyright (C) 2003-2005 M. Bakker,
8  * Ahead Software AG
9  */
10
11 /** \file aac_afh.c para_server's aac audio format handler. */
12
13 #include <regex.h>
14 #include <mp4v2/mp4v2.h>
15
16 #include "para.h"
17 #include <mp4ff.h>
18 #include "error.h"
19 #include "portable_io.h"
20 #include "afh.h"
21 #include "string.h"
22 #include "aac.h"
23 #include "fd.h"
24
25 struct aac_afh_context {
26         const void *map;
27         size_t mapsize;
28         size_t fpos;
29         int32_t track;
30         mp4ff_t *mp4ff;
31         mp4AudioSpecificConfig masc;
32         mp4ff_callback_t cb;
33 };
34
35 static uint32_t aac_afh_read_cb(void *user_data, void *dest, uint32_t want)
36 {
37         struct aac_afh_context *c = user_data;
38         uint32_t have, rv;
39
40         if (want == 0 || c->fpos >= c->mapsize) {
41                 PARA_INFO_LOG("failed attempt to read %u bytes @%zu\n", want,
42                         c->fpos);
43                 errno = EAGAIN;
44                 return -1;
45         }
46         have = c->mapsize - c->fpos;
47         rv = PARA_MIN(have, want);
48         PARA_DEBUG_LOG("reading %u bytes @%zu\n", rv, c->fpos);
49         memcpy(dest, c->map + c->fpos, rv);
50         c->fpos += rv;
51         return rv;
52 }
53
54 static uint32_t aac_afh_seek_cb(void *user_data, uint64_t pos)
55 {
56         struct aac_afh_context *c = user_data;
57         c->fpos = pos;
58         return 0;
59 }
60
61 static int32_t aac_afh_get_track(mp4ff_t *mp4ff, mp4AudioSpecificConfig *masc)
62 {
63         int32_t i, rc, num_tracks = mp4ff_total_tracks(mp4ff);
64
65         assert(num_tracks >= 0);
66         for (i = 0; i < num_tracks; i++) {
67                 unsigned char *buf = NULL;
68                 unsigned buf_size = 0;
69
70                 mp4ff_get_decoder_config(mp4ff, i, &buf, &buf_size);
71                 if (buf) {
72                         rc = NeAACDecAudioSpecificConfig(buf, buf_size, masc);
73                         free(buf);
74                         if (rc < 0)
75                                 continue;
76                         return i;
77                 }
78         }
79         return -1; /* no audio track */
80 }
81
82 static int aac_afh_open(const void *map, size_t mapsize, void **afh_context)
83 {
84         int ret;
85         struct aac_afh_context *c = para_malloc(sizeof(*c));
86
87         c->map = map;
88         c->mapsize = mapsize;
89         c->fpos = 0;
90         c->cb.read = aac_afh_read_cb;
91         c->cb.seek = aac_afh_seek_cb;
92         c->cb.user_data = c;
93
94         ret = -E_MP4FF_OPEN;
95         c->mp4ff = mp4ff_open_read(&c->cb);
96         if (!c->mp4ff)
97                 goto free_ctx;
98         c->track = aac_afh_get_track(c->mp4ff, &c->masc);
99         ret = -E_MP4FF_TRACK;
100         if (c->track < 0)
101                 goto close_mp4ff;
102         *afh_context = c;
103         return 0;
104 close_mp4ff:
105         mp4ff_close(c->mp4ff);
106 free_ctx:
107         free(c);
108         *afh_context = NULL;
109         return ret;
110 }
111
112 static void aac_afh_close(void *afh_context)
113 {
114         struct aac_afh_context *c = afh_context;
115         mp4ff_close(c->mp4ff);
116         free(c);
117 }
118
119 /**
120  * Libmp4ff function to reposition the file to the given sample.
121  *
122  * \param f The opaque handle returned by mp4ff_open_read().
123  * \param track The number of the (audio) track.
124  * \param sample Destination.
125  *
126  * We need this function to obtain the offset of the sample within the audio
127  * file. Unfortunately, it is not exposed in the mp4ff header.
128  *
129  * \return This function always returns 0.
130  */
131 int32_t mp4ff_set_sample_position(mp4ff_t *f, const int32_t track, const int32_t sample);
132
133 static int aac_afh_get_chunk(long unsigned chunk_num, void *afh_context,
134                 const char **buf, size_t *len)
135 {
136         struct aac_afh_context *c = afh_context;
137         int32_t ss;
138         size_t offset;
139
140         assert(chunk_num <= INT_MAX);
141         /* this function always returns zero */
142         mp4ff_set_sample_position(c->mp4ff, c->track, chunk_num);
143         offset = c->fpos;
144         ss = mp4ff_read_sample_getsize(c->mp4ff, c->track, chunk_num);
145         if (ss <= 0)
146                 return -E_MP4FF_BAD_SAMPLE;
147         assert(ss + offset <= c->mapsize);
148         *buf = c->map + offset;
149         *len = ss;
150         return 1;
151 }
152 static int aac_find_stsz(char *buf, size_t buflen, off_t *skip)
153 {
154         int i;
155
156         for (i = 0; i + 16 < buflen; i++) {
157                 char *p = buf + i;
158                 unsigned sample_count, sample_size;
159
160                 if (p[0] != 's' || p[1] != 't' || p[2] != 's' || p[3] != 'z')
161                         continue;
162                 PARA_DEBUG_LOG("found stsz@%d\n", i);
163                 i += 8;
164                 sample_size = read_u32_be(buf + i);
165                 PARA_DEBUG_LOG("sample size: %u\n", sample_size);
166                 i += 4;
167                 sample_count = read_u32_be(buf + i);
168                 i += 4;
169                 PARA_DEBUG_LOG("sample count: %u\n", sample_count);
170                 *skip = i;
171                 return sample_count;
172         }
173         return -E_STSZ;
174 }
175
176 static int atom_cmp(const char *buf1, const char *buf2)
177 {
178         return memcmp(buf1, buf2, 4)? 1 : 0;
179 }
180
181 static int read_atom_header(char *buf, uint64_t *subsize, char type[5])
182 {
183         uint64_t size = read_u32_be(buf);
184
185         memcpy(type, buf + 4, 4);
186         type[4] = '\0';
187
188         PARA_DEBUG_LOG("size: %llu, type: %s\n", (long long unsigned)size, type);
189         if (size != 1) {
190                 *subsize = size;
191                 return 8;
192         }
193         buf += 4;
194         size = 0;
195         size = read_u64_be(buf);
196         *subsize = size;
197         return 16;
198 }
199
200 static char *get_tag(char *p, int size)
201 {
202         char *buf;
203
204         assert(size > 0);
205         buf = para_malloc(size + 1);
206
207         memcpy(buf, p, size);
208         buf[size] = '\0';
209         PARA_DEBUG_LOG("size: %d: %s\n", size, buf);
210         return buf;
211 }
212
213 static void read_tags(char *buf, size_t buflen, struct afh_info *afhi)
214 {
215         char *p = buf;
216
217         while (p + 32 < buf + buflen) {
218                 char *q, type1[5], type2[5];
219                 uint64_t size1, size2;
220                 int ret, ret2;
221
222                 ret = read_atom_header(p, &size1, type1);
223                 ret2 = read_atom_header(p + ret, &size2, type2);
224
225                 if (size2 <= 16 || atom_cmp(type2, "data")) {
226                         p += size1;
227                         continue;
228                 }
229                 size2 -= 16;
230                 q = p + ret + ret2 + 8;
231                 if (q + size2 > buf + buflen)
232                         break;
233                 if (!atom_cmp(type1, "\xa9" "ART"))
234                         afhi->tags.artist = get_tag(q, size2);
235                 else if (!atom_cmp(type1, "\xa9" "alb"))
236                         afhi->tags.album = get_tag(q, size2);
237                 else if (!atom_cmp(type1, "\xa9" "nam"))
238                         afhi->tags.title = get_tag(q, size2);
239                 else if (!atom_cmp(type1, "\xa9" "cmt"))
240                         afhi->tags.comment = get_tag(q, size2);
241                 else if (!atom_cmp(type1, "\xa9" "day"))
242                         afhi->tags.year = get_tag(q, size2);
243                 p += size1;
244         }
245 }
246
247 static void read_meta(char *buf, size_t buflen, struct afh_info *afhi)
248 {
249         char *p = buf;
250
251         while (p + 4 < buf + buflen) {
252
253                 if (p[0] != 'i' || p[1] != 'l' || p[2] != 's' || p[3] != 't') {
254                         p++;
255                         continue;
256                 }
257                 p += 4;
258                 return read_tags(p, buflen - (p - buf), afhi);
259         }
260 }
261
262 static void aac_get_taginfo(char *buf, size_t buflen, struct afh_info *afhi)
263 {
264         int i;
265         uint64_t subsize;
266         char type[5];
267
268         for (i = 0; i + 24 < buflen; i++) {
269                 char *p = buf + i;
270                 if (p[0] != 'm' || p[1] != 'e' || p[2] != 't' || p[3] != 'a')
271                         continue;
272                 PARA_INFO_LOG("found metadata at offset %d\n", i);
273                 i += 8;
274                 p = buf + i;
275                 i += read_atom_header(p, &subsize, type);
276                 p = buf + i;
277                 return read_meta(p, buflen - i, afhi);
278         }
279         PARA_INFO_LOG("no meta data\n");
280 }
281
282 static ssize_t aac_compute_chunk_table(struct afh_info *afhi,
283                 char *map, size_t numbytes)
284 {
285         int ret, i;
286         size_t sum = 0;
287         off_t skip;
288
289         ret = aac_find_stsz(map, numbytes, &skip);
290         if (ret < 0)
291                 return ret;
292         afhi->chunks_total = ret;
293         PARA_DEBUG_LOG("sz table has %" PRIu32 " entries\n", afhi->chunks_total);
294         afhi->chunk_table = para_malloc((afhi->chunks_total + 1) * sizeof(size_t));
295         for (i = 1; i <= afhi->chunks_total; i++) {
296                 if (skip + 4 > numbytes)
297                         break;
298                 sum += read_u32_be(map + skip);
299                 afhi->chunk_table[i] = sum;
300                 skip += 4;
301 //              if (i < 10 || i + 10 > afhi->chunks_total)
302 //                      PARA_DEBUG_LOG("offset #%d: %zu\n", i, afhi->chunk_table[i]);
303         }
304         return skip;
305 }
306
307 static int aac_set_chunk_tv(struct afh_info *afhi,
308                 mp4AudioSpecificConfig *mp4ASC, uint32_t *seconds)
309 {
310         float tmp = mp4ASC->sbr_present_flag == 1? 2047 : 1023;
311         struct timeval total;
312         long unsigned ms;
313
314         ms = 1000.0 * afhi->chunks_total * tmp / mp4ASC->samplingFrequency;
315         ms2tv(ms, &total);
316         tv_divide(afhi->chunks_total, &total, &afhi->chunk_tv);
317         PARA_INFO_LOG("%luHz, %lus (%" PRIu32 " x %lums)\n",
318                 mp4ASC->samplingFrequency, ms / 1000,
319                 afhi->chunks_total, tv2ms(&afhi->chunk_tv));
320         if (ms < 1000)
321                 return -E_MP4ASC;
322         *seconds = ms / 1000;
323         return 1;
324 }
325
326 /*
327  * Init m4a file and write some tech data to given pointers.
328  */
329 static int aac_get_file_info(char *map, size_t numbytes, __a_unused int fd,
330                 struct afh_info *afhi)
331 {
332         int i;
333         size_t skip;
334         ssize_t ret;
335         unsigned long rate = 0, decoder_len;
336         unsigned char channels = 0;
337         mp4AudioSpecificConfig mp4ASC;
338         NeAACDecHandle handle = NULL;
339
340         ret = aac_find_esds(map, numbytes, &skip, &decoder_len);
341         if (ret < 0)
342                 goto out;
343         aac_get_taginfo(map, numbytes, afhi);
344         handle = aac_open();
345         ret = -E_AAC_AFH_INIT;
346         if (NeAACDecInit(handle, (unsigned char *)map + skip, decoder_len,
347                         &rate, &channels))
348                 goto out;
349         if (!channels)
350                 goto out;
351         PARA_DEBUG_LOG("rate: %lu, channels: %d\n", rate, channels);
352         ret = -E_MP4ASC;
353         if (NeAACDecAudioSpecificConfig((unsigned char *)map + skip,
354                         numbytes - skip, &mp4ASC))
355                 goto out;
356         if (!mp4ASC.samplingFrequency)
357                 goto out;
358         ret = aac_compute_chunk_table(afhi, map, numbytes);
359         if (ret < 0)
360                 goto out;
361         skip = ret;
362         ret = aac_set_chunk_tv(afhi, &mp4ASC, &afhi->seconds_total);
363         if (ret < 0)
364                 goto out;
365         ret = aac_find_entry_point(map + skip, numbytes - skip, &skip);
366         if (ret < 0)
367                 goto out;
368         afhi->chunk_table[0] = ret;
369         for (i = 1; i<= afhi->chunks_total; i++)
370                 afhi->chunk_table[i] += ret;
371         set_max_chunk_size(afhi);
372         afhi->channels = channels;
373         afhi->frequency = rate;
374         ret = (afhi->chunk_table[afhi->chunks_total] - afhi->chunk_table[0]) * 8; /* bits */
375         ret += (channels * afhi->seconds_total * 500); /* avoid rounding error */
376         afhi->bitrate = ret / (channels * afhi->seconds_total * 1000);
377         ret = 1;
378 out:
379         if (handle)
380                 NeAACDecClose(handle);
381         return ret;
382 }
383
384 static int aac_rewrite_tags(const char *map, size_t mapsize,
385                 struct taginfo *tags, int fd, const char *filename)
386 {
387         MP4FileHandle h;
388         const MP4Tags *mdata;
389         int ret = write_all(fd, map, mapsize);
390
391         if (ret < 0)
392                 return ret;
393         lseek(fd, 0, SEEK_SET);
394         h = MP4Modify(filename, 0);
395         if (!h) {
396                 PARA_ERROR_LOG("MP4Modify() failed, fd = %d\n", fd);
397                 return -E_MP4V2;
398         }
399         mdata = MP4TagsAlloc();
400         assert(mdata);
401         if (!MP4TagsFetch(mdata, h)) {
402                 PARA_ERROR_LOG("MP4Tags_Fetch() failed\n");
403                 ret = -E_MP4V2;
404                 goto close;
405         }
406
407         if (!MP4TagsSetAlbum(mdata, tags->album)) {
408                 PARA_ERROR_LOG("Could not set album\n");
409                 ret = -E_MP4V2;
410                 goto tags_free;
411         }
412         if (!MP4TagsSetArtist(mdata, tags->artist)) {
413                 PARA_ERROR_LOG("Could not set album\n");
414                 ret = -E_MP4V2;
415                 goto tags_free;
416         }
417         if (!MP4TagsSetComments(mdata, tags->comment)) {
418                 PARA_ERROR_LOG("Could not set comment\n");
419                 ret = -E_MP4V2;
420                 goto tags_free;
421         }
422         if (!MP4TagsSetName(mdata, tags->title)) {
423                 PARA_ERROR_LOG("Could not set title\n");
424                 ret = -E_MP4V2;
425                 goto tags_free;
426         }
427         if (!MP4TagsSetReleaseDate(mdata, tags->year)) {
428                 PARA_ERROR_LOG("Could not set release date\n");
429                 ret = -E_MP4V2;
430                 goto tags_free;
431         }
432
433         if (!MP4TagsStore(mdata, h)) {
434                 PARA_ERROR_LOG("Could not store tags\n");
435                 ret = -E_MP4V2;
436                 goto tags_free;
437         }
438         ret = 1;
439 tags_free:
440         MP4TagsFree(mdata);
441 close:
442         MP4Close(h, 0);
443         return ret;
444 }
445
446 static const char * const aac_suffixes[] = {"m4a", "mp4", NULL};
447 /**
448  * the init function of the aac audio format handler
449  *
450  * \param afh pointer to the struct to initialize
451  */
452 void aac_afh_init(struct audio_format_handler *afh)
453 {
454         afh->get_file_info = aac_get_file_info,
455         afh->suffixes = aac_suffixes;
456         afh->rewrite_tags = aac_rewrite_tags;
457         afh->open = aac_afh_open;
458         afh->get_chunk = aac_afh_get_chunk;
459         afh->close = aac_afh_close;
460 }