FFmpeg  3.4.9
aadec.c
Go to the documentation of this file.
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;
46  struct AVTEA *tea_ctx;
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 
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};
80  AVIOContext *pb = s->pb;
81  AVStream *st;
82  int ret;
83 
84  /* parse .aa header */
85  avio_skip(pb, 4); // file size
86  avio_skip(pb, 4); // magic string
87  toc_size = avio_rb32(pb); // TOC size
88  avio_skip(pb, 4); // unidentified integer
89  if (toc_size > MAX_TOC_ENTRIES || toc_size < 2)
90  return AVERROR_INVALIDDATA;
91  for (i = 0; i < toc_size; i++) { // read TOC
92  avio_skip(pb, 4); // TOC entry index
93  TOC[i].offset = avio_rb32(pb); // block offset
94  TOC[i].size = avio_rb32(pb); // block size
95  }
96  avio_skip(pb, 24); // header termination block (ignored)
97  npairs = avio_rb32(pb); // read dictionary entries
98  if (npairs > MAX_DICTIONARY_ENTRIES)
99  return AVERROR_INVALIDDATA;
100  for (i = 0; i < npairs; i++) {
101  memset(val, 0, sizeof(val));
102  memset(key, 0, sizeof(key));
103  avio_skip(pb, 1); // unidentified integer
104  nkey = avio_rb32(pb); // key string length
105  nval = avio_rb32(pb); // value string length
106  avio_get_str(pb, nkey, key, sizeof(key));
107  avio_get_str(pb, nval, val, sizeof(val));
108  if (!strcmp(key, "codec")) {
109  av_log(s, AV_LOG_DEBUG, "Codec is <%s>\n", val);
110  strncpy(codec_name, val, sizeof(codec_name) - 1);
111  } else if (!strcmp(key, "HeaderSeed")) {
112  av_log(s, AV_LOG_DEBUG, "HeaderSeed is <%s>\n", val);
113  header_seed = atoi(val);
114  } else if (!strcmp(key, "HeaderKey")) { // this looks like "1234567890 1234567890 1234567890 1234567890"
115  av_log(s, AV_LOG_DEBUG, "HeaderKey is <%s>\n", val);
116 
117  ret = sscanf(val, "%"SCNu32"%"SCNu32"%"SCNu32"%"SCNu32,
118  &header_key_part[0], &header_key_part[1], &header_key_part[2], &header_key_part[3]);
119  if (ret != 4)
120  return AVERROR_INVALIDDATA;
121 
122  for (idx = 0; idx < 4; idx++) {
123  AV_WB32(&header_key[idx * 4], header_key_part[idx]); // convert each part to BE!
124  }
125  av_log(s, AV_LOG_DEBUG, "Processed HeaderKey is ");
126  for (i = 0; i < 16; i++)
127  av_log(s, AV_LOG_DEBUG, "%02x", header_key[i]);
128  av_log(s, AV_LOG_DEBUG, "\n");
129  } else {
130  av_dict_set(&s->metadata, key, val, 0);
131  }
132  }
133 
134  /* verify fixed key */
135  if (c->aa_fixed_key_len != 16) {
136  av_log(s, AV_LOG_ERROR, "aa_fixed_key value needs to be 16 bytes!\n");
137  return AVERROR(EINVAL);
138  }
139 
140  /* verify codec */
141  if ((c->codec_second_size = get_second_size(codec_name)) == -1) {
142  av_log(s, AV_LOG_ERROR, "unknown codec <%s>!\n", codec_name);
143  return AVERROR(EINVAL);
144  }
145 
146  /* decryption key derivation */
147  c->tea_ctx = av_tea_alloc();
148  if (!c->tea_ctx)
149  return AVERROR(ENOMEM);
150  av_tea_init(c->tea_ctx, c->aa_fixed_key, 16);
151  output[0] = output[1] = 0; // purely for padding purposes
152  memcpy(output + 2, header_key, 16);
153  idx = 0;
154  for (i = 0; i < 3; i++) { // TEA CBC with weird mixed endianness
155  AV_WB32(src, header_seed);
156  AV_WB32(src + 4, header_seed + 1);
157  header_seed += 2;
158  av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 0); // TEA ECB encrypt
159  for (j = 0; j < TEA_BLOCK_SIZE && idx < 18; j+=1, idx+=1) {
160  output[idx] = output[idx] ^ dst[j];
161  }
162  }
163  memcpy(c->file_key, output + 2, 16); // skip first 2 bytes of output
164  av_log(s, AV_LOG_DEBUG, "File key is ");
165  for (i = 0; i < 16; i++)
166  av_log(s, AV_LOG_DEBUG, "%02x", c->file_key[i]);
167  av_log(s, AV_LOG_DEBUG, "\n");
168 
169  /* decoder setup */
170  st = avformat_new_stream(s, NULL);
171  if (!st) {
172  av_freep(&c->tea_ctx);
173  return AVERROR(ENOMEM);
174  }
176  if (!strcmp(codec_name, "mp332")) {
178  st->codecpar->sample_rate = 22050;
180  st->start_time = 0;
181  } else if (!strcmp(codec_name, "acelp85")) {
183  st->codecpar->block_align = 19;
184  st->codecpar->channels = 1;
185  st->codecpar->sample_rate = 8500;
187  } else if (!strcmp(codec_name, "acelp16")) {
189  st->codecpar->block_align = 20;
190  st->codecpar->channels = 1;
191  st->codecpar->sample_rate = 16000;
193  }
194 
195  /* determine, and jump to audio start offset */
196  for (i = 1; i < toc_size; i++) { // skip the first entry!
197  current_size = TOC[i].size;
198  if (current_size > largest_size) {
199  largest_idx = i;
200  largest_size = current_size;
201  }
202  }
203  start = TOC[largest_idx].offset;
204  avio_seek(pb, start, SEEK_SET);
205  c->current_chapter_size = 0;
206 
207  return 0;
208 }
209 
211 {
212  uint8_t dst[TEA_BLOCK_SIZE];
214  int i;
215  int trailing_bytes;
216  int blocks;
218  int written = 0;
219  int ret;
220  AADemuxContext *c = s->priv_data;
221 
222  // are we at the start of a chapter?
223  if (c->current_chapter_size == 0) {
225  if (c->current_chapter_size == 0) {
226  return AVERROR_EOF;
227  }
228  av_log(s, AV_LOG_DEBUG, "Chapter %d (%" PRId64 " bytes)\n", c->chapter_idx, c->current_chapter_size);
229  c->chapter_idx = c->chapter_idx + 1;
230  avio_skip(s->pb, 4); // data start offset
232  }
233 
234  // is this the last block in this chapter?
237  }
238 
239  // decrypt c->current_codec_second_size bytes
241  for (i = 0; i < blocks; i++) {
242  avio_read(s->pb, src, TEA_BLOCK_SIZE);
243  av_tea_init(c->tea_ctx, c->file_key, 16);
244  av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 1);
245  memcpy(buf + written, dst, TEA_BLOCK_SIZE);
246  written = written + TEA_BLOCK_SIZE;
247  }
248  trailing_bytes = c->current_codec_second_size % TEA_BLOCK_SIZE;
249  if (trailing_bytes != 0) { // trailing bytes are left unencrypted!
250  avio_read(s->pb, src, trailing_bytes);
251  memcpy(buf + written, src, trailing_bytes);
252  written = written + trailing_bytes;
253  }
254 
255  // update state
257  if (c->current_chapter_size <= 0)
258  c->current_chapter_size = 0;
259 
260  ret = av_new_packet(pkt, written);
261  if (ret < 0)
262  return ret;
263  memcpy(pkt->data, buf, written);
264 
265  return 0;
266 }
267 
268 static int aa_probe(AVProbeData *p)
269 {
270  uint8_t *buf = p->buf;
271 
272  // first 4 bytes are file size, next 4 bytes are the magic
273  if (AV_RB32(buf+4) != AA_MAGIC)
274  return 0;
275 
276  return AVPROBE_SCORE_MAX / 2;
277 }
278 
280 {
281  AADemuxContext *c = s->priv_data;
282 
283  av_freep(&c->tea_ctx);
284 
285  return 0;
286 }
287 
288 #define OFFSET(x) offsetof(AADemuxContext, x)
289 static const AVOption aa_options[] = {
290  { "aa_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
291  "Fixed key used for handling Audible AA files", OFFSET(aa_fixed_key),
292  AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd2a51d673"},
293  .flags = AV_OPT_FLAG_DECODING_PARAM },
294  { NULL },
295 };
296 
297 static const AVClass aa_class = {
298  .class_name = "aa",
299  .item_name = av_default_item_name,
300  .option = aa_options,
301  .version = LIBAVUTIL_VERSION_INT,
302 };
303 
305  .name = "aa",
306  .long_name = NULL_IF_CONFIG_SMALL("Audible AA format files"),
307  .priv_class = &aa_class,
308  .priv_data_size = sizeof(AADemuxContext),
309  .extensions = "aa",
310  .read_probe = aa_probe,
315 };
#define NULL
Definition: coverity.c:32
const char const char void * val
Definition: avisynth_c.h:771
const char * s
Definition: avisynth_c.h:768
Bytestream IO Context.
Definition: avio.h:161
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int size
AVOption.
Definition: opt.h:246
#define LIBAVUTIL_VERSION_INT
Definition: version.h:86
uint8_t file_key[16]
Definition: aadec.c:47
#define AA_MAGIC
Definition: aadec.c:33
static int aa_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: aadec.c:210
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: avcodec.h:4152
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:244
int current_codec_second_size
Definition: aadec.c:44
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: aviobuf.c:329
static AVPacket pkt
#define src
Definition: vp8dsp.c:254
struct AVTEA * av_tea_alloc(void)
Allocate an AVTEA context To free the struct: av_free(ptr)
Definition: tea.c:35
Format I/O context.
Definition: avformat.h:1349
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
Public dictionary API.
uint8_t
static int aa_probe(AVProbeData *p)
Definition: aadec.c:268
AVOptions.
#define MAX_CODEC_SECOND_SIZE
Definition: aadec.c:34
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:789
#define AV_RB32
Definition: intreadwrite.h:130
static const AVOption aa_options[]
Definition: aadec.c:289
enum AVStreamParseType need_parsing
Definition: avformat.h:1081
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4383
Definition: tea.c:30
uint8_t * data
Definition: avcodec.h:1679
static int flags
Definition: log.c:57
#define AVERROR_EOF
End of file.
Definition: error.h:55
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
AVInputFormat ff_aa_demuxer
Definition: aadec.c:304
full parsing and repack with timestamp and position generation by parser for raw this assumes that ea...
Definition: avformat.h:814
#define av_log(a,...)
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:636
int av_new_packet(AVPacket *pkt, int size)
Allocate the payload of a packet and initialize its fields with default values.
Definition: avpacket.c:86
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
AVDictionary * metadata
Metadata that applies to the whole file.
Definition: avformat.h:1567
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:181
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:557
enum AVMediaType codec_type
General type of the encoded data.
Definition: avcodec.h:4148
static int aa_read_header(AVFormatContext *s)
Definition: aadec.c:66
uint8_t * aa_fixed_key
Definition: aadec.c:41
static const uint8_t offset[127][2]
Definition: vf_spp.c:92
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:463
int64_t current_chapter_size
Definition: aadec.c:48
int block_align
Audio only.
Definition: avcodec.h:4269
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:55
Public header for libavutil TEA algorithm.
void av_tea_crypt(AVTEA *ctx, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt)
Encrypt or decrypt a buffer using a previously initialized context.
Definition: tea.c:95
struct AVTEA * tea_ctx
Definition: aadec.c:46
#define MAX_DICTIONARY_ENTRIES
Definition: aadec.c:36
#define OFFSET(x)
Definition: aadec.c:288
offset must point to a pointer immediately followed by an int for the length
Definition: opt.h:229
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:528
static int aa_read_close(AVFormatContext *s)
Definition: aadec.c:279
Stream structure.
Definition: avformat.h:889
static int read_packet(void *opaque, uint8_t *buf, int buf_size)
Definition: avio_reading.c:42
AVIOContext * pb
I/O context.
Definition: avformat.h:1391
#define MAX_TOC_ENTRIES
Definition: aadec.c:35
void * buf
Definition: avisynth_c.h:690
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
Describe the class of an AVClass context structure.
Definition: log.h:67
#define AV_WB32(p, v)
Definition: intreadwrite.h:424
#define AVFMT_GENERIC_INDEX
Use generic index building code.
Definition: avformat.h:487
#define AV_OPT_FLAG_DECODING_PARAM
a generic parameter which can be set by the user for demuxing or decoding
Definition: opt.h:277
static int get_second_size(char *codec_name)
Definition: aadec.c:51
static const AVClass aa_class
Definition: aadec.c:297
This structure contains the data a format has to probe a file.
Definition: avformat.h:461
int chapter_idx
Definition: aadec.c:45
int sample_rate
Audio only.
Definition: avcodec.h:4262
#define AVPROBE_SCORE_MAX
maximum score
Definition: avformat.h:473
Main libavformat public API header.
void av_tea_init(AVTEA *ctx, const uint8_t key[16], int rounds)
Initialize an AVTEA context.
Definition: tea.c:42
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base...
Definition: avformat.h:936
static double c[64]
#define TEA_BLOCK_SIZE
Definition: aadec.c:37
int codec_second_size
Definition: aadec.c:43
uint32_t key[16]
Definition: tea.c:31
int aa_fixed_key_len
Definition: aadec.c:42
void * priv_data
Format private data.
Definition: avformat.h:1377
int channels
Audio only.
Definition: avcodec.h:4258
#define av_freep(p)
void INT64 start
Definition: avisynth_c.h:690
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:664
AVCodecParameters * codecpar
Definition: avformat.h:1252
int avio_get_str(AVIOContext *pb, int maxlen, char *buf, int buflen)
Read a string from pb into buf.
Definition: aviobuf.c:814
This structure stores compressed data.
Definition: avcodec.h:1656