Merge branch 'refs/heads/t/command_handler_cleanups'
[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 "error.h"
18 #include "afh.h"
19 #include "string.h"
20 #include "aac.h"
21 #include "fd.h"
22
23 static int aac_find_stsz(unsigned char *buf, size_t buflen, off_t *skip)
24 {
25         int i;
26
27         for (i = 0; i + 16 < buflen; i++) {
28                 unsigned char *p = buf + i;
29                 unsigned sample_count, sample_size;
30
31                 if (p[0] != 's' || p[1] != 't' || p[2] != 's' || p[3] != 'z')
32                         continue;
33                 PARA_DEBUG_LOG("found stsz@%d\n", i);
34                 i += 8;
35                 sample_size = aac_read_int32(buf + i);
36                 PARA_DEBUG_LOG("sample size: %d\n", sample_size);
37                 i += 4;
38                 sample_count = aac_read_int32(buf + i);
39                 i += 4;
40                 PARA_DEBUG_LOG("sample count: %d\n", sample_count);
41                 *skip = i;
42                 return sample_count;
43         }
44         return -E_STSZ;
45 }
46
47 static int atom_cmp(const unsigned char *buf1, const char *buf2)
48 {
49         const unsigned char *b2 = (unsigned char *)buf2;
50
51         if (buf1[0] != b2[0])
52                 return 1;
53         if (buf1[1] != b2[1])
54                 return 1;
55         if (buf1[2] != b2[2])
56                 return 1;
57         if (buf1[3] != b2[3])
58                 return 1;
59         return 0;
60 }
61
62 static int read_atom_header(unsigned char *buf, uint64_t *subsize, unsigned char type[5])
63 {
64         int i;
65         uint64_t size = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
66
67         memcpy(type, buf + 4, 4);
68         type[4] = '\0';
69
70         PARA_DEBUG_LOG("size: %llu, type: %s\n", (long long unsigned)size, type);
71         if (size != 1) {
72                 *subsize = size;
73                 return 8;
74         }
75         buf += 4;
76         size = 0;
77         for (i = 0; i < 8; i++)
78                 size |= ((uint64_t)buf[i]) << ((7 - i) * 8);
79         *subsize = size;
80         return 16;
81 }
82
83 static char *get_tag(unsigned char *p, int size)
84 {
85         char *buf;
86
87         assert(size > 0);
88         buf = para_malloc(size + 1);
89
90         memcpy(buf, p, size);
91         buf[size] = '\0';
92         PARA_DEBUG_LOG("size: %d: %s\n", size, buf);
93         return buf;
94 }
95
96 static void read_tags(unsigned char *buf, size_t buflen, struct afh_info *afhi)
97 {
98         unsigned char *p = buf;
99
100         while (p + 32 < buf + buflen) {
101                 unsigned char *q, type1[5], type2[5];
102                 uint64_t size1, size2;
103                 int ret, ret2;
104
105                 ret = read_atom_header(p, &size1, type1);
106                 ret2 = read_atom_header(p + ret, &size2, type2);
107
108                 if (size2 <= 16 || atom_cmp(type2, "data")) {
109                         p += size1;
110                         continue;
111                 }
112                 size2 -= 16;
113                 q = p + ret + ret2 + 8;
114                 if (q + size2 > buf + buflen)
115                         break;
116                 if (!atom_cmp(type1, "\xa9" "ART"))
117                         afhi->tags.artist = get_tag(q, size2);
118                 else if (!atom_cmp(type1, "\xa9" "alb"))
119                         afhi->tags.album = get_tag(q, size2);
120                 else if (!atom_cmp(type1, "\xa9" "nam"))
121                         afhi->tags.title = get_tag(q, size2);
122                 else if (!atom_cmp(type1, "\xa9" "cmt"))
123                         afhi->tags.comment = get_tag(q, size2);
124                 else if (!atom_cmp(type1, "\xa9" "day"))
125                         afhi->tags.year = get_tag(q, size2);
126                 p += size1;
127         }
128 }
129
130 static void read_meta(unsigned char *buf, size_t buflen, struct afh_info *afhi)
131 {
132         unsigned char *p = buf;
133
134         while (p + 4 < buf + buflen) {
135
136                 if (p[0] != 'i' || p[1] != 'l' || p[2] != 's' || p[3] != 't') {
137                         p++;
138                         continue;
139                 }
140                 p += 4;
141                 return read_tags(p, buflen - (p - buf), afhi);
142         }
143 }
144
145 static void aac_get_taginfo(unsigned char *buf, size_t buflen,
146                 struct afh_info *afhi)
147 {
148         int i;
149         uint64_t subsize;
150         unsigned char type[5];
151
152         for (i = 0; i + 24 < buflen; i++) {
153                 unsigned char *p = buf + i;
154                 if (p[0] != 'm' || p[1] != 'e' || p[2] != 't' || p[3] != 'a')
155                         continue;
156                 PARA_INFO_LOG("found metadata at offset %d\n", i);
157                 i += 8;
158                 p = buf + i;
159                 i += read_atom_header(p, &subsize, type);
160                 p = buf + i;
161                 return read_meta(p, buflen - i, afhi);
162         }
163         PARA_INFO_LOG("no meta data\n");
164 }
165
166 static ssize_t aac_compute_chunk_table(struct afh_info *afhi,
167                 unsigned char *map, size_t numbytes)
168 {
169         int ret, i;
170         size_t sum = 0;
171         off_t skip;
172
173         ret = aac_find_stsz(map, numbytes, &skip);
174         if (ret < 0)
175                 return ret;
176         afhi->chunks_total = ret;
177         PARA_DEBUG_LOG("sz table has %lu entries\n", afhi->chunks_total);
178         afhi->chunk_table = para_malloc((afhi->chunks_total + 1) * sizeof(size_t));
179         for (i = 1; i <= afhi->chunks_total; i++) {
180                 if (skip + 4 > numbytes)
181                         break;
182                 sum += aac_read_int32(map + skip);
183                 afhi->chunk_table[i] = sum;
184                 skip += 4;
185 //              if (i < 10 || i + 10 > afhi->chunks_total)
186 //                      PARA_DEBUG_LOG("offset #%d: %zu\n", i, afhi->chunk_table[i]);
187         }
188         return skip;
189 }
190
191 static int aac_set_chunk_tv(struct afh_info *afhi,
192                 mp4AudioSpecificConfig *mp4ASC, long unsigned *seconds)
193 {
194         float tmp = mp4ASC->sbr_present_flag == 1? 2047 : 1023;
195         struct timeval total;
196         long unsigned ms;
197
198         if (!mp4ASC->samplingFrequency)
199                 return -E_MP4ASC;
200         ms = 1000.0 * afhi->chunks_total * tmp / mp4ASC->samplingFrequency;
201         ms2tv(ms, &total);
202         tv_divide(afhi->chunks_total, &total, &afhi->chunk_tv);
203         PARA_INFO_LOG("%luHz, %lus (%lu x %lums)\n",
204                 mp4ASC->samplingFrequency, ms / 1000,
205                 afhi->chunks_total, tv2ms(&afhi->chunk_tv));
206         if (ms < 1000)
207                 return -E_MP4ASC;
208         *seconds = ms / 1000;
209         return 1;
210 }
211
212 /*
213  * Init m4a file and write some tech data to given pointers.
214  */
215 static int aac_get_file_info(char *map, size_t numbytes, __a_unused int fd,
216                 struct afh_info *afhi)
217 {
218         int i;
219         size_t skip;
220         ssize_t ret;
221         unsigned long rate = 0, decoder_len;
222         unsigned char channels = 0;
223         mp4AudioSpecificConfig mp4ASC;
224         NeAACDecHandle handle = NULL;
225         unsigned char *umap = (unsigned char *) map;
226
227         ret = aac_find_esds(umap, numbytes, &skip, &decoder_len);
228         if (ret < 0)
229                 goto out;
230         aac_get_taginfo(umap, numbytes, afhi);
231         handle = aac_open();
232         ret = -E_AAC_AFH_INIT;
233         if (NeAACDecInit(handle, umap + skip, decoder_len, &rate, &channels))
234                 goto out;
235         if (!channels)
236                 goto out;
237         PARA_DEBUG_LOG("rate: %lu, channels: %d\n", rate, channels);
238         ret = -E_MP4ASC;
239         if (NeAACDecAudioSpecificConfig(umap + skip, numbytes - skip, &mp4ASC))
240                 goto out;
241         if (!mp4ASC.samplingFrequency)
242                 goto out;
243         ret = aac_compute_chunk_table(afhi, umap, numbytes);
244         if (ret < 0)
245                 goto out;
246         skip = ret;
247         ret = aac_set_chunk_tv(afhi, &mp4ASC, &afhi->seconds_total);
248         if (ret < 0)
249                 goto out;
250         ret = aac_find_entry_point(umap + skip, numbytes - skip, &skip);
251         if (ret < 0)
252                 goto out;
253         afhi->chunk_table[0] = ret;
254         for (i = 1; i<= afhi->chunks_total; i++)
255                 afhi->chunk_table[i] += ret;
256         afhi->channels = channels;
257         afhi->frequency = rate;
258         ret = (afhi->chunk_table[afhi->chunks_total] - afhi->chunk_table[0]) * 8; /* bits */
259         ret += (channels * afhi->seconds_total * 500); /* avoid rounding error */
260         afhi->bitrate = ret / (channels * afhi->seconds_total * 1000);
261         ret = 1;
262 out:
263         if (handle)
264                 NeAACDecClose(handle);
265         return ret;
266 }
267
268 static int aac_rewrite_tags(const char *map, size_t mapsize,
269                 struct taginfo *tags, int fd, const char *filename)
270 {
271         MP4FileHandle h;
272         const MP4Tags *mdata;
273         int ret = write_all(fd, map, mapsize);
274
275         if (ret < 0)
276                 return ret;
277         lseek(fd, 0, SEEK_SET);
278         h = MP4Modify(filename, 0);
279         if (!h) {
280                 PARA_ERROR_LOG("MP4Modify() failed, fd = %d\n", fd);
281                 return -E_MP4V2;
282         }
283         mdata = MP4TagsAlloc();
284         assert(mdata);
285         if (!MP4TagsFetch(mdata, h)) {
286                 PARA_ERROR_LOG("MP4Tags_Fetch() failed\n");
287                 ret = -E_MP4V2;
288                 goto close;
289         }
290
291         if (!MP4TagsSetAlbum(mdata, tags->album)) {
292                 PARA_ERROR_LOG("Could not set album\n");
293                 ret = -E_MP4V2;
294                 goto tags_free;
295         }
296         if (!MP4TagsSetArtist(mdata, tags->artist)) {
297                 PARA_ERROR_LOG("Could not set album\n");
298                 ret = -E_MP4V2;
299                 goto tags_free;
300         }
301         if (!MP4TagsSetComments(mdata, tags->comment)) {
302                 PARA_ERROR_LOG("Could not set comment\n");
303                 ret = -E_MP4V2;
304                 goto tags_free;
305         }
306         if (!MP4TagsSetName(mdata, tags->title)) {
307                 PARA_ERROR_LOG("Could not set title\n");
308                 ret = -E_MP4V2;
309                 goto tags_free;
310         }
311         if (!MP4TagsSetReleaseDate(mdata, tags->year)) {
312                 PARA_ERROR_LOG("Could not set release date\n");
313                 ret = -E_MP4V2;
314                 goto tags_free;
315         }
316
317         if (!MP4TagsStore(mdata, h)) {
318                 PARA_ERROR_LOG("Could not store tags\n");
319                 ret = -E_MP4V2;
320                 goto tags_free;
321         }
322         ret = 1;
323 tags_free:
324         MP4TagsFree(mdata);
325 close:
326         MP4Close(h, 0);
327         return ret;
328 }
329
330 static const char* aac_suffixes[] = {"m4a", "mp4", NULL};
331 /**
332  * the init function of the aac audio format handler
333  *
334  * \param afh pointer to the struct to initialize
335  */
336 void aac_afh_init(struct audio_format_handler *afh)
337 {
338         afh->get_file_info = aac_get_file_info,
339         afh->suffixes = aac_suffixes;
340         afh->rewrite_tags = aac_rewrite_tags;
341 }