]> git.sesse.net Git - ffmpeg/blob - libavformat/aadec.c
Merge commit '5292e97c42b05db7ad4e51c1ea756b12fdf721ff'
[ffmpeg] / libavformat / aadec.c
1 /*
2  * Audible AA demuxer
3  * Copyright (c) 2015 Vesselin Bontchev
4  *
5  * Header parsing is borrowed from https://github.com/jteeuwen/audible project.
6  * Copyright (c) 2001-2014, Jim Teeuwen
7  *
8  * Redistribution and use in source and binary forms, with or without modification,
9  * are permitted provided that the following conditions are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright notice, this
12  *    list of conditions and the following disclaimer.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
18  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
20  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
21  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
23  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "avformat.h"
27 #include "internal.h"
28 #include "libavutil/dict.h"
29 #include "libavutil/intreadwrite.h"
30 #include "libavutil/tea.h"
31 #include "libavutil/opt.h"
32
33 #define AA_MAGIC 1469084982 /* this identifies an audible .aa file */
34 #define MAX_CODEC_SECOND_SIZE 3982
35 #define MAX_TOC_ENTRIES 16
36 #define MAX_DICTIONARY_ENTRIES 128
37 #define TEA_BLOCK_SIZE 8
38
39 typedef struct AADemuxContext {
40     AVClass *class;
41     uint8_t *aa_fixed_key;
42     int aa_fixed_key_len;
43     int codec_second_size;
44     int current_codec_second_size;
45     int chapter_idx;
46     struct AVTEA *tea_ctx;
47     uint8_t file_key[16];
48     int64_t current_chapter_size;
49 } AADemuxContext;
50
51 static int get_second_size(char *codec_name)
52 {
53     int result = -1;
54
55     if (!strcmp(codec_name, "mp332")) {
56         result = 3982;
57     } else if (!strcmp(codec_name, "acelp16")) {
58         result = 2000;
59     } else if (!strcmp(codec_name, "acelp85")) {
60         result = 1045;
61     }
62
63     return result;
64 }
65
66 static int aa_read_header(AVFormatContext *s)
67 {
68     int i, j, idx, largest_idx = -1;
69     uint32_t nkey, nval, toc_size, npairs, header_seed = 0, start;
70     char key[128], val[128], codec_name[64] = {0};
71     uint8_t output[24], dst[8], src[8];
72     int64_t largest_size = -1, current_size = -1;
73     struct toc_entry {
74         uint32_t offset;
75         uint32_t size;
76     } TOC[MAX_TOC_ENTRIES];
77     uint32_t header_key_part[4];
78     uint8_t header_key[16] = {0};
79     AADemuxContext *c = s->priv_data;
80     AVIOContext *pb = s->pb;
81     AVStream *st;
82
83     /* parse .aa header */
84     avio_skip(pb, 4); // file size
85     avio_skip(pb, 4); // magic string
86     toc_size = avio_rb32(pb); // TOC size
87     avio_skip(pb, 4); // unidentified integer
88     if (toc_size > MAX_TOC_ENTRIES)
89         return AVERROR_INVALIDDATA;
90     for (i = 0; i < toc_size; i++) { // read TOC
91         avio_skip(pb, 4); // TOC entry index
92         TOC[i].offset = avio_rb32(pb); // block offset
93         TOC[i].size = avio_rb32(pb); // block size
94     }
95     avio_skip(pb, 24); // header termination block (ignored)
96     npairs = avio_rb32(pb); // read dictionary entries
97     if (npairs > MAX_DICTIONARY_ENTRIES)
98         return AVERROR_INVALIDDATA;
99     for (i = 0; i < npairs; i++) {
100         memset(val, 0, sizeof(val));
101         memset(key, 0, sizeof(key));
102         avio_skip(pb, 1); // unidentified integer
103         nkey = avio_rb32(pb); // key string length
104         nval = avio_rb32(pb); // value string length
105         avio_get_str(pb, nkey, key, sizeof(key));
106         avio_get_str(pb, nval, val, sizeof(val));
107         if (!strcmp(key, "codec")) {
108             av_log(s, AV_LOG_DEBUG, "Codec is <%s>\n", val);
109             strncpy(codec_name, val, sizeof(codec_name) - 1);
110         } else if (!strcmp(key, "HeaderSeed")) {
111             av_log(s, AV_LOG_DEBUG, "HeaderSeed is <%s>\n", val);
112             header_seed = atoi(val);
113         } else if (!strcmp(key, "HeaderKey")) { // this looks like "1234567890 1234567890 1234567890 1234567890"
114             av_log(s, AV_LOG_DEBUG, "HeaderKey is <%s>\n", val);
115             sscanf(val, "%"SCNu32"%"SCNu32"%"SCNu32"%"SCNu32,
116                    &header_key_part[0], &header_key_part[1], &header_key_part[2], &header_key_part[3]);
117             for (idx = 0; idx < 4; idx++) {
118                 AV_WB32(&header_key[idx * 4], header_key_part[idx]); // convert each part to BE!
119             }
120             av_log(s, AV_LOG_DEBUG, "Processed HeaderKey is ");
121             for (i = 0; i < 16; i++)
122                 av_log(s, AV_LOG_DEBUG, "%02x", header_key[i]);
123             av_log(s, AV_LOG_DEBUG, "\n");
124         } else {
125             av_dict_set(&s->metadata, key, val, 0);
126         }
127     }
128
129     /* verify fixed key */
130     if (c->aa_fixed_key_len != 16) {
131         av_log(s, AV_LOG_ERROR, "aa_fixed_key value needs to be 16 bytes!\n");
132         return AVERROR(EINVAL);
133     }
134
135     /* verify codec */
136     if ((c->codec_second_size = get_second_size(codec_name)) == -1) {
137         av_log(s, AV_LOG_ERROR, "unknown codec <%s>!\n", codec_name);
138         return AVERROR(EINVAL);
139     }
140
141     /* decryption key derivation */
142     c->tea_ctx = av_tea_alloc();
143     if (!c->tea_ctx)
144         return AVERROR(ENOMEM);
145     av_tea_init(c->tea_ctx, c->aa_fixed_key, 16);
146     output[0] = output[1] = 0; // purely for padding purposes
147     memcpy(output + 2, header_key, 16);
148     idx = 0;
149     for (i = 0; i < 3; i++) { // TEA CBC with weird mixed endianness
150         AV_WB32(src, header_seed);
151         AV_WB32(src + 4, header_seed + 1);
152         header_seed += 2;
153         av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 0); // TEA ECB encrypt
154         for (j = 0; j < TEA_BLOCK_SIZE && idx < 18; j+=1, idx+=1) {
155             output[idx] = output[idx] ^ dst[j];
156         }
157     }
158     memcpy(c->file_key, output + 2, 16); // skip first 2 bytes of output
159     av_log(s, AV_LOG_DEBUG, "File key is ");
160     for (i = 0; i < 16; i++)
161         av_log(s, AV_LOG_DEBUG, "%02x", c->file_key[i]);
162     av_log(s, AV_LOG_DEBUG, "\n");
163
164     /* decoder setup */
165     st = avformat_new_stream(s, NULL);
166     if (!st) {
167         av_freep(&c->tea_ctx);
168         return AVERROR(ENOMEM);
169     }
170     st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
171     if (!strcmp(codec_name, "mp332")) {
172         st->codecpar->codec_id = AV_CODEC_ID_MP3;
173         st->codecpar->sample_rate = 22050;
174         st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
175         st->start_time = 0;
176     } else if (!strcmp(codec_name, "acelp85")) {
177         st->codecpar->codec_id = AV_CODEC_ID_SIPR;
178         st->codecpar->block_align = 19;
179         st->codecpar->channels = 1;
180         st->codecpar->sample_rate = 8500;
181         st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
182     } else if (!strcmp(codec_name, "acelp16")) {
183         st->codecpar->codec_id = AV_CODEC_ID_SIPR;
184         st->codecpar->block_align = 20;
185         st->codecpar->channels = 1;
186         st->codecpar->sample_rate = 16000;
187         st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
188     }
189
190     /* determine, and jump to audio start offset */
191     for (i = 1; i < toc_size; i++) { // skip the first entry!
192         current_size = TOC[i].size;
193         if (current_size > largest_size) {
194             largest_idx = i;
195             largest_size = current_size;
196         }
197     }
198     start = TOC[largest_idx].offset;
199     avio_seek(pb, start, SEEK_SET);
200     c->current_chapter_size = 0;
201
202     return 0;
203 }
204
205 static int aa_read_packet(AVFormatContext *s, AVPacket *pkt)
206 {
207     uint8_t dst[TEA_BLOCK_SIZE];
208     uint8_t src[TEA_BLOCK_SIZE];
209     int i;
210     int trailing_bytes;
211     int blocks;
212     uint8_t buf[MAX_CODEC_SECOND_SIZE * 2];
213     int written = 0;
214     int ret;
215     AADemuxContext *c = s->priv_data;
216
217     // are we at the start of a chapter?
218     if (c->current_chapter_size == 0) {
219         c->current_chapter_size = avio_rb32(s->pb);
220         if (c->current_chapter_size == 0) {
221             return AVERROR_EOF;
222         }
223         av_log(s, AV_LOG_DEBUG, "Chapter %d (%" PRId64 " bytes)\n", c->chapter_idx, c->current_chapter_size);
224         c->chapter_idx = c->chapter_idx + 1;
225         avio_skip(s->pb, 4); // data start offset
226         c->current_codec_second_size = c->codec_second_size;
227     }
228
229     // is this the last block in this chapter?
230     if (c->current_chapter_size / c->current_codec_second_size == 0) {
231         c->current_codec_second_size = c->current_chapter_size % c->current_codec_second_size;
232     }
233
234     // decrypt c->current_codec_second_size bytes
235     blocks = c->current_codec_second_size / TEA_BLOCK_SIZE;
236     for (i = 0; i < blocks; i++) {
237         avio_read(s->pb, src, TEA_BLOCK_SIZE);
238         av_tea_init(c->tea_ctx, c->file_key, 16);
239         av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 1);
240         memcpy(buf + written, dst, TEA_BLOCK_SIZE);
241         written = written + TEA_BLOCK_SIZE;
242     }
243     trailing_bytes = c->current_codec_second_size % TEA_BLOCK_SIZE;
244     if (trailing_bytes != 0) { // trailing bytes are left unencrypted!
245         avio_read(s->pb, src, trailing_bytes);
246         memcpy(buf + written, src, trailing_bytes);
247         written = written + trailing_bytes;
248     }
249
250     // update state
251     c->current_chapter_size = c->current_chapter_size - c->current_codec_second_size;
252     if (c->current_chapter_size <= 0)
253         c->current_chapter_size = 0;
254
255     ret = av_new_packet(pkt, written);
256     if (ret < 0)
257         return ret;
258     memcpy(pkt->data, buf, written);
259
260     return 0;
261 }
262
263 static int aa_probe(AVProbeData *p)
264 {
265     uint8_t *buf = p->buf;
266
267     // first 4 bytes are file size, next 4 bytes are the magic
268     if (AV_RB32(buf+4) != AA_MAGIC)
269         return 0;
270
271     return AVPROBE_SCORE_MAX / 2;
272 }
273
274 static int aa_read_close(AVFormatContext *s)
275 {
276     AADemuxContext *c = s->priv_data;
277
278     av_freep(&c->tea_ctx);
279
280     return 0;
281 }
282
283 #define OFFSET(x) offsetof(AADemuxContext, x)
284 static const AVOption aa_options[] = {
285     { "aa_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
286         "Fixed key used for handling Audible AA files", OFFSET(aa_fixed_key),
287         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd2a51d673"},
288         .flags = AV_OPT_FLAG_DECODING_PARAM },
289     { NULL },
290 };
291
292 static const AVClass aa_class = {
293     .class_name = "aa",
294     .item_name  = av_default_item_name,
295     .option     = aa_options,
296     .version    = LIBAVUTIL_VERSION_INT,
297 };
298
299 AVInputFormat ff_aa_demuxer = {
300     .name           = "aa",
301     .long_name      = NULL_IF_CONFIG_SMALL("Audible AA format files"),
302     .priv_class     = &aa_class,
303     .priv_data_size = sizeof(AADemuxContext),
304     .extensions     = "aa",
305     .read_probe     = aa_probe,
306     .read_header    = aa_read_header,
307     .read_packet    = aa_read_packet,
308     .read_close     = aa_read_close,
309     .flags          = AVFMT_GENERIC_INDEX,
310 };