]> git.sesse.net Git - ffmpeg/blob - libavformat/aadec.c
Merge commit '7b1ae0e73ab7f7c5eabc70dbe2e579127c6e154f'
[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/intreadwrite.h"
29 #include "libavutil/tea.h"
30 #include "libavutil/opt.h"
31
32 #define AA_MAGIC 1469084982 /* this identifies an audible .aa file */
33 #define MAX_CODEC_SECOND_SIZE 3982
34 #define MAX_TOC_ENTRIES 16
35 #define MAX_DICTIONARY_ENTRIES 128
36 #define TEA_BLOCK_SIZE 8
37
38 typedef struct AADemuxContext {
39     AVClass *class;
40     uint8_t *aa_fixed_key;
41     int aa_fixed_key_len;
42     int codec_second_size;
43     int current_codec_second_size;
44     int chapter_idx;
45     struct AVTEA *tea_ctx;
46     uint8_t file_key[16];
47     int64_t current_chapter_size;
48 } AADemuxContext;
49
50 static int get_second_size(char *codec_name)
51 {
52     int result = -1;
53
54     if (!strcmp(codec_name, "mp332")) {
55         result = 3982;
56     } else if (!strcmp(codec_name, "acelp16")) {
57         result = 2000;
58     } else if (!strcmp(codec_name, "acelp85")) {
59         result = 1045;
60     }
61
62     return result;
63 }
64
65 static int aa_read_header(AVFormatContext *s)
66 {
67     int i, j, idx, largest_idx = -1;
68     uint32_t nkey, nval, toc_size, npairs, header_seed = 0, start;
69     char key[128], val[128], codec_name[64] = {0};
70     uint8_t output[24], dst[8], src[8];
71     int64_t largest_size = -1, current_size = -1;
72     struct toc_entry {
73         uint32_t offset;
74         uint32_t size;
75     } TOC[MAX_TOC_ENTRIES];
76     uint32_t header_key_part[4];
77     uint8_t header_key[16] = {0};
78     AADemuxContext *c = s->priv_data;
79     AVIOContext *pb = s->pb;
80     AVStream *st;
81
82     /* parse .aa header */
83     avio_skip(pb, 4); // file size
84     avio_skip(pb, 4); // magic string
85     toc_size = avio_rb32(pb); // TOC size
86     avio_skip(pb, 4); // unidentified integer
87     if (toc_size > MAX_TOC_ENTRIES)
88         return AVERROR_INVALIDDATA;
89     for (i = 0; i < toc_size; i++) { // read TOC
90         avio_skip(pb, 4); // TOC entry index
91         TOC[i].offset = avio_rb32(pb); // block offset
92         TOC[i].size = avio_rb32(pb); // block size
93     }
94     avio_skip(pb, 24); // header termination block (ignored)
95     npairs = avio_rb32(pb); // read dictionary entries
96     if (npairs > MAX_DICTIONARY_ENTRIES)
97         return AVERROR_INVALIDDATA;
98     for (i = 0; i < npairs; i++) {
99         memset(val, 0, sizeof(val));
100         memset(key, 0, sizeof(key));
101         avio_skip(pb, 1); // unidentified integer
102         nkey = avio_rb32(pb); // key string length
103         nval = avio_rb32(pb); // value string length
104         if (nkey > sizeof(key)) {
105             avio_skip(pb, nkey);
106         } else {
107             avio_read(pb, key, nkey); // key string
108         }
109         if (nval > sizeof(val)) {
110             avio_skip(pb, nval);
111         } else {
112             avio_read(pb, val, nval); // value string
113         }
114         if (!strcmp(key, "codec")) {
115             av_log(s, AV_LOG_DEBUG, "Codec is <%s>\n", val);
116             strncpy(codec_name, val, sizeof(codec_name) - 1);
117         }
118         if (!strcmp(key, "HeaderSeed")) {
119             av_log(s, AV_LOG_DEBUG, "HeaderSeed is <%s>\n", val);
120             header_seed = atoi(val);
121         }
122         if (!strcmp(key, "HeaderKey")) { // this looks like "1234567890 1234567890 1234567890 1234567890"
123             av_log(s, AV_LOG_DEBUG, "HeaderKey is <%s>\n", val);
124             sscanf(val, "%u%u%u%u", &header_key_part[0], &header_key_part[1], &header_key_part[2], &header_key_part[3]);
125             for (idx = 0; idx < 4; idx++) {
126                 AV_WB32(&header_key[idx * 4], header_key_part[idx]); // convert each part to BE!
127             }
128             av_log(s, AV_LOG_DEBUG, "Processed HeaderKey is ");
129             for (i = 0; i < 16; i++)
130                 av_log(s, AV_LOG_DEBUG, "%02x", header_key[i]);
131             av_log(s, AV_LOG_DEBUG, "\n");
132         }
133     }
134
135     /* verify fixed key */
136     if (c->aa_fixed_key_len != 16) {
137         av_log(s, AV_LOG_ERROR, "aa_fixed_key value needs to be 16 bytes!\n");
138         return AVERROR(EINVAL);
139     }
140
141     /* verify codec */
142     if ((c->codec_second_size = get_second_size(codec_name)) == -1) {
143         av_log(s, AV_LOG_ERROR, "unknown codec <%s>!\n", codec_name);
144         return AVERROR(EINVAL);
145     }
146
147     /* decryption key derivation */
148     c->tea_ctx = av_tea_alloc();
149     if (!c->tea_ctx)
150         return AVERROR(ENOMEM);
151     av_tea_init(c->tea_ctx, c->aa_fixed_key, 16);
152     output[0] = output[1] = 0; // purely for padding purposes
153     memcpy(output + 2, header_key, 16);
154     idx = 0;
155     for (i = 0; i < 3; i++) { // TEA CBC with weird mixed endianness
156         AV_WB32(src, header_seed);
157         AV_WB32(src + 4, header_seed + 1);
158         header_seed += 2;
159         av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 0); // TEA ECB encrypt
160         for (j = 0; j < TEA_BLOCK_SIZE && idx < 18; j+=1, idx+=1) {
161             output[idx] = output[idx] ^ dst[j];
162         }
163     }
164     memcpy(c->file_key, output + 2, 16); // skip first 2 bytes of output
165     av_log(s, AV_LOG_DEBUG, "File key is ");
166     for (i = 0; i < 16; i++)
167         av_log(s, AV_LOG_DEBUG, "%02x", c->file_key[i]);
168     av_log(s, AV_LOG_DEBUG, "\n");
169
170     /* decoder setup */
171     st = avformat_new_stream(s, NULL);
172     if (!st) {
173         av_freep(&c->tea_ctx);
174         return AVERROR(ENOMEM);
175     }
176     st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
177     if (!strcmp(codec_name, "mp332")) {
178         st->codecpar->codec_id = AV_CODEC_ID_MP3;
179         st->codecpar->sample_rate = 22050;
180         st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
181         st->start_time = 0;
182     } else if (!strcmp(codec_name, "acelp85")) {
183         st->codecpar->codec_id = AV_CODEC_ID_SIPR;
184         st->codecpar->block_align = 19;
185         st->codecpar->channels = 1;
186         st->codecpar->sample_rate = 8500;
187     } else if (!strcmp(codec_name, "acelp16")) {
188         st->codecpar->codec_id = AV_CODEC_ID_SIPR;
189         st->codecpar->block_align = 20;
190         st->codecpar->channels = 1;
191         st->codecpar->sample_rate = 16000;
192     }
193
194     /* determine, and jump to audio start offset */
195     for (i = 1; i < toc_size; i++) { // skip the first entry!
196         current_size = TOC[i].size;
197         if (current_size > largest_size) {
198             largest_idx = i;
199             largest_size = current_size;
200         }
201     }
202     start = TOC[largest_idx].offset;
203     avio_seek(pb, start, SEEK_SET);
204     c->current_chapter_size = 0;
205
206     return 0;
207 }
208
209 static int aa_read_packet(AVFormatContext *s, AVPacket *pkt)
210 {
211     uint8_t dst[TEA_BLOCK_SIZE];
212     uint8_t src[TEA_BLOCK_SIZE];
213     int i;
214     int trailing_bytes;
215     int blocks;
216     uint8_t buf[MAX_CODEC_SECOND_SIZE * 2];
217     int written = 0;
218     int ret;
219     AADemuxContext *c = s->priv_data;
220
221     // are we at the start of a chapter?
222     if (c->current_chapter_size == 0) {
223         c->current_chapter_size = avio_rb32(s->pb);
224         if (c->current_chapter_size == 0) {
225             return AVERROR_EOF;
226         }
227         av_log(s, AV_LOG_DEBUG, "Chapter %d (%" PRId64 " bytes)\n", c->chapter_idx, c->current_chapter_size);
228         c->chapter_idx = c->chapter_idx + 1;
229         avio_skip(s->pb, 4); // data start offset
230         c->current_codec_second_size = c->codec_second_size;
231     }
232
233     // is this the last block in this chapter?
234     if (c->current_chapter_size / c->current_codec_second_size == 0) {
235         c->current_codec_second_size = c->current_chapter_size % c->current_codec_second_size;
236     }
237
238     // decrypt c->current_codec_second_size bytes
239     blocks = c->current_codec_second_size / TEA_BLOCK_SIZE;
240     for (i = 0; i < blocks; i++) {
241         avio_read(s->pb, src, TEA_BLOCK_SIZE);
242         av_tea_init(c->tea_ctx, c->file_key, 16);
243         av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 1);
244         memcpy(buf + written, dst, TEA_BLOCK_SIZE);
245         written = written + TEA_BLOCK_SIZE;
246     }
247     trailing_bytes = c->current_codec_second_size % TEA_BLOCK_SIZE;
248     if (trailing_bytes != 0) { // trailing bytes are left unencrypted!
249         avio_read(s->pb, src, trailing_bytes);
250         memcpy(buf + written, src, trailing_bytes);
251         written = written + trailing_bytes;
252     }
253
254     // update state
255     c->current_chapter_size = c->current_chapter_size - c->current_codec_second_size;
256     if (c->current_chapter_size <= 0)
257         c->current_chapter_size = 0;
258
259     ret = av_new_packet(pkt, written);
260     if (ret < 0)
261         return ret;
262     memcpy(pkt->data, buf, written);
263
264     return 0;
265 }
266
267 static int aa_probe(AVProbeData *p)
268 {
269     uint8_t *buf = p->buf;
270
271     // first 4 bytes are file size, next 4 bytes are the magic
272     if (AV_RB32(buf+4) != AA_MAGIC)
273         return 0;
274
275     return AVPROBE_SCORE_MAX / 2;
276 }
277
278 static int aa_read_close(AVFormatContext *s)
279 {
280     AADemuxContext *c = s->priv_data;
281
282     av_freep(&c->tea_ctx);
283
284     return 0;
285 }
286
287 #define OFFSET(x) offsetof(AADemuxContext, x)
288 static const AVOption aa_options[] = {
289     { "aa_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
290         "Fixed key used for handling Audible AA files", OFFSET(aa_fixed_key),
291         AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd2a51d673"},
292         .flags = AV_OPT_FLAG_DECODING_PARAM },
293     { NULL },
294 };
295
296 static const AVClass aa_class = {
297     .class_name = "aa",
298     .item_name  = av_default_item_name,
299     .option     = aa_options,
300     .version    = LIBAVUTIL_VERSION_INT,
301 };
302
303 AVInputFormat ff_aa_demuxer = {
304     .name           = "aa",
305     .long_name      = NULL_IF_CONFIG_SMALL("Audible AA format files"),
306     .priv_class     = &aa_class,
307     .priv_data_size = sizeof(AADemuxContext),
308     .extensions     = "aa",
309     .read_probe     = aa_probe,
310     .read_header    = aa_read_header,
311     .read_packet    = aa_read_packet,
312     .read_close     = aa_read_close,
313     .flags          = AVFMT_GENERIC_INDEX,
314 };