afh: Dynamic chunks.
[paraslash.git] / aac_afh.c
index f354a63ce9c3c34b95d32d19bc588bd1134470eb..bcf7b785e4bd5518d751b22d5b368e296e43c662 100644 (file)
--- a/aac_afh.c
+++ b/aac_afh.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2014 Andre Noll <maan@systemlinux.org>
+ * Copyright (C) 2006 Andre Noll <maan@tuebingen.mpg.de>
  *
  * Licensed under the GPL v2. For licencing details see COPYING.
  */
 /** \file aac_afh.c para_server's aac audio format handler. */
 
 #include <regex.h>
+#include <mp4v2/mp4v2.h>
 
 #include "para.h"
+#include <mp4ff.h>
 #include "error.h"
+#include "portable_io.h"
 #include "afh.h"
 #include "string.h"
 #include "aac.h"
+#include "fd.h"
 
-static int aac_find_stsz(unsigned char *buf, size_t buflen, off_t *skip)
+struct aac_afh_context {
+       const void *map;
+       size_t mapsize;
+       size_t fpos;
+       int32_t track;
+       mp4ff_t *mp4ff;
+       mp4AudioSpecificConfig masc;
+       mp4ff_callback_t cb;
+};
+
+static uint32_t aac_afh_read_cb(void *user_data, void *dest, uint32_t want)
+{
+       struct aac_afh_context *c = user_data;
+       uint32_t have, rv;
+
+       if (want == 0 || c->fpos >= c->mapsize) {
+               PARA_INFO_LOG("failed attempt to read %u bytes @%zu\n", want,
+                       c->fpos);
+               errno = EAGAIN;
+               return -1;
+       }
+       have = c->mapsize - c->fpos;
+       rv = PARA_MIN(have, want);
+       PARA_DEBUG_LOG("reading %u bytes @%zu\n", rv, c->fpos);
+       memcpy(dest, c->map + c->fpos, rv);
+       c->fpos += rv;
+       return rv;
+}
+
+static uint32_t aac_afh_seek_cb(void *user_data, uint64_t pos)
+{
+       struct aac_afh_context *c = user_data;
+       c->fpos = pos;
+       return 0;
+}
+
+static int32_t aac_afh_get_track(mp4ff_t *mp4ff, mp4AudioSpecificConfig *masc)
+{
+       int32_t i, rc, num_tracks = mp4ff_total_tracks(mp4ff);
+
+       assert(num_tracks >= 0);
+       for (i = 0; i < num_tracks; i++) {
+               unsigned char *buf = NULL;
+               unsigned buf_size = 0;
+
+               mp4ff_get_decoder_config(mp4ff, i, &buf, &buf_size);
+               if (buf) {
+                       rc = NeAACDecAudioSpecificConfig(buf, buf_size, masc);
+                       free(buf);
+                       if (rc < 0)
+                               continue;
+                       return i;
+               }
+       }
+       return -1; /* no audio track */
+}
+
+static int aac_afh_open(const void *map, size_t mapsize, void **afh_context)
+{
+       int ret;
+       struct aac_afh_context *c = para_malloc(sizeof(*c));
+
+       c->map = map;
+       c->mapsize = mapsize;
+       c->fpos = 0;
+       c->cb.read = aac_afh_read_cb;
+       c->cb.seek = aac_afh_seek_cb;
+       c->cb.user_data = c;
+
+       ret = -E_MP4FF_OPEN;
+       c->mp4ff = mp4ff_open_read(&c->cb);
+       if (!c->mp4ff)
+               goto free_ctx;
+       c->track = aac_afh_get_track(c->mp4ff, &c->masc);
+       ret = -E_MP4FF_TRACK;
+       if (c->track < 0)
+               goto close_mp4ff;
+       *afh_context = c;
+       return 0;
+close_mp4ff:
+       mp4ff_close(c->mp4ff);
+free_ctx:
+       free(c);
+       *afh_context = NULL;
+       return ret;
+}
+
+static void aac_afh_close(void *afh_context)
+{
+       struct aac_afh_context *c = afh_context;
+       mp4ff_close(c->mp4ff);
+       free(c);
+}
+
+/**
+ * Libmp4ff function to reposition the file to the given sample.
+ *
+ * \param f The opaque handle returned by mp4ff_open_read().
+ * \param track The number of the (audio) track.
+ * \param sample Destination.
+ *
+ * We need this function to obtain the offset of the sample within the audio
+ * file. Unfortunately, it is not exposed in the mp4ff header.
+ *
+ * \return This function always returns 0.
+ */
+int32_t mp4ff_set_sample_position(mp4ff_t *f, const int32_t track, const int32_t sample);
+
+static int aac_afh_get_chunk(long unsigned chunk_num, void *afh_context,
+               const char **buf, size_t *len)
+{
+       struct aac_afh_context *c = afh_context;
+       int32_t ss;
+       size_t offset;
+
+       assert(chunk_num <= INT_MAX);
+       /* this function always returns zero */
+       mp4ff_set_sample_position(c->mp4ff, c->track, chunk_num);
+       offset = c->fpos;
+       ss = mp4ff_read_sample_getsize(c->mp4ff, c->track, chunk_num);
+       if (ss <= 0)
+               return -E_MP4FF_BAD_SAMPLE;
+       assert(ss + offset <= c->mapsize);
+       *buf = c->map + offset;
+       *len = ss;
+       return 1;
+}
+static int aac_find_stsz(char *buf, size_t buflen, off_t *skip)
 {
        int i;
 
        for (i = 0; i + 16 < buflen; i++) {
-               unsigned char *p = buf + i;
+               char *p = buf + i;
                unsigned sample_count, sample_size;
 
                if (p[0] != 's' || p[1] != 't' || p[2] != 's' || p[3] != 'z')
                        continue;
                PARA_DEBUG_LOG("found stsz@%d\n", i);
                i += 8;
-               sample_size = aac_read_int32(buf + i);
-               PARA_DEBUG_LOG("sample size: %d\n", sample_size);
+               sample_size = read_u32_be(buf + i);
+               PARA_DEBUG_LOG("sample size: %u\n", sample_size);
                i += 4;
-               sample_count = aac_read_int32(buf + i);
+               sample_count = read_u32_be(buf + i);
                i += 4;
-               PARA_DEBUG_LOG("sample count: %d\n", sample_count);
+               PARA_DEBUG_LOG("sample count: %u\n", sample_count);
                *skip = i;
                return sample_count;
        }
        return -E_STSZ;
 }
 
-static int atom_cmp(const unsigned char *buf1, const char *buf2)
+static int atom_cmp(const char *buf1, const char *buf2)
 {
-       const unsigned char *b2 = (unsigned char *)buf2;
-
-       if (buf1[0] != b2[0])
-               return 1;
-       if (buf1[1] != b2[1])
-               return 1;
-       if (buf1[2] != b2[2])
-               return 1;
-       if (buf1[3] != b2[3])
-               return 1;
-       return 0;
+       return memcmp(buf1, buf2, 4)? 1 : 0;
 }
 
-static int read_atom_header(unsigned char *buf, uint64_t *subsize, unsigned char type[5])
+static int read_atom_header(char *buf, uint64_t *subsize, char type[5])
 {
-       int i;
-       uint64_t size = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
+       uint64_t size = read_u32_be(buf);
 
        memcpy(type, buf + 4, 4);
        type[4] = '\0';
@@ -72,13 +192,12 @@ static int read_atom_header(unsigned char *buf, uint64_t *subsize, unsigned char
        }
        buf += 4;
        size = 0;
-       for (i = 0; i < 8; i++)
-               size |= ((uint64_t)buf[i]) << ((7 - i) * 8);
+       size = read_u64_be(buf);
        *subsize = size;
        return 16;
 }
 
-static char *get_tag(unsigned char *p, int size)
+static char *get_tag(char *p, int size)
 {
        char *buf;
 
@@ -91,12 +210,12 @@ static char *get_tag(unsigned char *p, int size)
        return buf;
 }
 
-static void read_tags(unsigned char *buf, size_t buflen, struct afh_info *afhi)
+static void read_tags(char *buf, size_t buflen, struct afh_info *afhi)
 {
-       unsigned char *p = buf;
+       char *p = buf;
 
        while (p + 32 < buf + buflen) {
-               unsigned char *q, type1[5], type2[5];
+               char *q, type1[5], type2[5];
                uint64_t size1, size2;
                int ret, ret2;
 
@@ -125,9 +244,9 @@ static void read_tags(unsigned char *buf, size_t buflen, struct afh_info *afhi)
        }
 }
 
-static void read_meta(unsigned char *buf, size_t buflen, struct afh_info *afhi)
+static void read_meta(char *buf, size_t buflen, struct afh_info *afhi)
 {
-       unsigned char *p = buf;
+       char *p = buf;
 
        while (p + 4 < buf + buflen) {
 
@@ -140,15 +259,14 @@ static void read_meta(unsigned char *buf, size_t buflen, struct afh_info *afhi)
        }
 }
 
-static void aac_get_taginfo(unsigned char *buf, size_t buflen,
-               struct afh_info *afhi)
+static void aac_get_taginfo(char *buf, size_t buflen, struct afh_info *afhi)
 {
        int i;
        uint64_t subsize;
-       unsigned char type[5];
+       char type[5];
 
        for (i = 0; i + 24 < buflen; i++) {
-               unsigned char *p = buf + i;
+               char *p = buf + i;
                if (p[0] != 'm' || p[1] != 'e' || p[2] != 't' || p[3] != 'a')
                        continue;
                PARA_INFO_LOG("found metadata at offset %d\n", i);
@@ -162,7 +280,7 @@ static void aac_get_taginfo(unsigned char *buf, size_t buflen,
 }
 
 static ssize_t aac_compute_chunk_table(struct afh_info *afhi,
-               unsigned char *map, size_t numbytes)
+               char *map, size_t numbytes)
 {
        int ret, i;
        size_t sum = 0;
@@ -172,12 +290,12 @@ static ssize_t aac_compute_chunk_table(struct afh_info *afhi,
        if (ret < 0)
                return ret;
        afhi->chunks_total = ret;
-       PARA_DEBUG_LOG("sz table has %lu entries\n", afhi->chunks_total);
+       PARA_DEBUG_LOG("sz table has %" PRIu32 " entries\n", afhi->chunks_total);
        afhi->chunk_table = para_malloc((afhi->chunks_total + 1) * sizeof(size_t));
        for (i = 1; i <= afhi->chunks_total; i++) {
                if (skip + 4 > numbytes)
                        break;
-               sum += aac_read_int32(map + skip);
+               sum += read_u32_be(map + skip);
                afhi->chunk_table[i] = sum;
                skip += 4;
 //             if (i < 10 || i + 10 > afhi->chunks_total)
@@ -187,18 +305,16 @@ static ssize_t aac_compute_chunk_table(struct afh_info *afhi,
 }
 
 static int aac_set_chunk_tv(struct afh_info *afhi,
-               mp4AudioSpecificConfig *mp4ASC, long unsigned *seconds)
+               mp4AudioSpecificConfig *mp4ASC, uint32_t *seconds)
 {
        float tmp = mp4ASC->sbr_present_flag == 1? 2047 : 1023;
        struct timeval total;
        long unsigned ms;
 
-       if (!mp4ASC->samplingFrequency)
-               return -E_MP4ASC;
        ms = 1000.0 * afhi->chunks_total * tmp / mp4ASC->samplingFrequency;
        ms2tv(ms, &total);
        tv_divide(afhi->chunks_total, &total, &afhi->chunk_tv);
-       PARA_INFO_LOG("%luHz, %lus (%lu x %lums)\n",
+       PARA_INFO_LOG("%luHz, %lus (%" PRIu32 " x %lums)\n",
                mp4ASC->samplingFrequency, ms / 1000,
                afhi->chunks_total, tv2ms(&afhi->chunk_tv));
        if (ms < 1000)
@@ -220,37 +336,39 @@ static int aac_get_file_info(char *map, size_t numbytes, __a_unused int fd,
        unsigned char channels = 0;
        mp4AudioSpecificConfig mp4ASC;
        NeAACDecHandle handle = NULL;
-       unsigned char *umap = (unsigned char *) map;
 
-       ret = aac_find_esds(umap, numbytes, &skip, &decoder_len);
+       ret = aac_find_esds(map, numbytes, &skip, &decoder_len);
        if (ret < 0)
                goto out;
-       aac_get_taginfo(umap, numbytes, afhi);
+       aac_get_taginfo(map, numbytes, afhi);
        handle = aac_open();
        ret = -E_AAC_AFH_INIT;
-       if (NeAACDecInit(handle, umap + skip, decoder_len, &rate, &channels))
+       if (NeAACDecInit(handle, (unsigned char *)map + skip, decoder_len,
+                       &rate, &channels))
                goto out;
        if (!channels)
                goto out;
        PARA_DEBUG_LOG("rate: %lu, channels: %d\n", rate, channels);
        ret = -E_MP4ASC;
-       if (NeAACDecAudioSpecificConfig(umap + skip, numbytes - skip, &mp4ASC))
+       if (NeAACDecAudioSpecificConfig((unsigned char *)map + skip,
+                       numbytes - skip, &mp4ASC))
                goto out;
        if (!mp4ASC.samplingFrequency)
                goto out;
-       ret = aac_compute_chunk_table(afhi, umap, numbytes);
+       ret = aac_compute_chunk_table(afhi, map, numbytes);
        if (ret < 0)
                goto out;
        skip = ret;
        ret = aac_set_chunk_tv(afhi, &mp4ASC, &afhi->seconds_total);
        if (ret < 0)
                goto out;
-       ret = aac_find_entry_point(umap + skip, numbytes - skip, &skip);
+       ret = aac_find_entry_point(map + skip, numbytes - skip, &skip);
        if (ret < 0)
                goto out;
        afhi->chunk_table[0] = ret;
        for (i = 1; i<= afhi->chunks_total; i++)
                afhi->chunk_table[i] += ret;
+       set_max_chunk_size(afhi);
        afhi->channels = channels;
        afhi->frequency = rate;
        ret = (afhi->chunk_table[afhi->chunks_total] - afhi->chunk_table[0]) * 8; /* bits */
@@ -263,7 +381,69 @@ out:
        return ret;
 }
 
-static const char* aac_suffixes[] = {"m4a", "mp4", NULL};
+static int aac_rewrite_tags(const char *map, size_t mapsize,
+               struct taginfo *tags, int fd, const char *filename)
+{
+       MP4FileHandle h;
+       const MP4Tags *mdata;
+       int ret = write_all(fd, map, mapsize);
+
+       if (ret < 0)
+               return ret;
+       lseek(fd, 0, SEEK_SET);
+       h = MP4Modify(filename, 0);
+       if (!h) {
+               PARA_ERROR_LOG("MP4Modify() failed, fd = %d\n", fd);
+               return -E_MP4V2;
+       }
+       mdata = MP4TagsAlloc();
+       assert(mdata);
+       if (!MP4TagsFetch(mdata, h)) {
+               PARA_ERROR_LOG("MP4Tags_Fetch() failed\n");
+               ret = -E_MP4V2;
+               goto close;
+       }
+
+       if (!MP4TagsSetAlbum(mdata, tags->album)) {
+               PARA_ERROR_LOG("Could not set album\n");
+               ret = -E_MP4V2;
+               goto tags_free;
+       }
+       if (!MP4TagsSetArtist(mdata, tags->artist)) {
+               PARA_ERROR_LOG("Could not set album\n");
+               ret = -E_MP4V2;
+               goto tags_free;
+       }
+       if (!MP4TagsSetComments(mdata, tags->comment)) {
+               PARA_ERROR_LOG("Could not set comment\n");
+               ret = -E_MP4V2;
+               goto tags_free;
+       }
+       if (!MP4TagsSetName(mdata, tags->title)) {
+               PARA_ERROR_LOG("Could not set title\n");
+               ret = -E_MP4V2;
+               goto tags_free;
+       }
+       if (!MP4TagsSetReleaseDate(mdata, tags->year)) {
+               PARA_ERROR_LOG("Could not set release date\n");
+               ret = -E_MP4V2;
+               goto tags_free;
+       }
+
+       if (!MP4TagsStore(mdata, h)) {
+               PARA_ERROR_LOG("Could not store tags\n");
+               ret = -E_MP4V2;
+               goto tags_free;
+       }
+       ret = 1;
+tags_free:
+       MP4TagsFree(mdata);
+close:
+       MP4Close(h, 0);
+       return ret;
+}
+
+static const char * const aac_suffixes[] = {"m4a", "mp4", NULL};
 /**
  * the init function of the aac audio format handler
  *
@@ -273,4 +453,8 @@ void aac_afh_init(struct audio_format_handler *afh)
 {
        afh->get_file_info = aac_get_file_info,
        afh->suffixes = aac_suffixes;
+       afh->rewrite_tags = aac_rewrite_tags;
+       afh->open = aac_afh_open;
+       afh->get_chunk = aac_afh_get_chunk;
+       afh->close = aac_afh_close;
 }