You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

419 lines
15KB

  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. #include "avformat.h"
  26. #include "internal.h"
  27. #include "libavutil/dict.h"
  28. #include "libavutil/intreadwrite.h"
  29. #include "libavutil/tea.h"
  30. #include "libavutil/opt.h"
  31. #define AA_MAGIC 1469084982 /* this identifies an audible .aa file */
  32. #define MAX_CODEC_SECOND_SIZE 3982
  33. #define MAX_TOC_ENTRIES 16
  34. #define MAX_DICTIONARY_ENTRIES 128
  35. #define TEA_BLOCK_SIZE 8
  36. #define CHAPTER_HEADER_SIZE 8
  37. #define TIMEPREC 1000
  38. #define MP3_FRAME_SIZE 104
  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. int64_t content_start;
  50. int64_t content_end;
  51. int seek_offset;
  52. } AADemuxContext;
  53. static int get_second_size(char *codec_name)
  54. {
  55. int result = -1;
  56. if (!strcmp(codec_name, "mp332")) {
  57. result = 3982;
  58. } else if (!strcmp(codec_name, "acelp16")) {
  59. result = 2000;
  60. } else if (!strcmp(codec_name, "acelp85")) {
  61. result = 1045;
  62. }
  63. return result;
  64. }
  65. static int aa_read_header(AVFormatContext *s)
  66. {
  67. int i, j, idx, largest_idx = -1;
  68. uint32_t toc_size, npairs, header_seed = 0, start;
  69. char codec_name[64] = {0};
  70. uint8_t output[24], dst[8], src[8];
  71. int64_t largest_size = -1, current_size = -1, chapter_pos;
  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. int ret;
  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 || toc_size < 2)
  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. char key[128], val[128];
  100. uint32_t nkey, nval;
  101. avio_skip(pb, 1); // unidentified integer
  102. nkey = avio_rb32(pb); // key string length
  103. nval = avio_rb32(pb); // value string length
  104. avio_get_str(pb, nkey, key, sizeof(key));
  105. avio_get_str(pb, nval, val, sizeof(val));
  106. if (!strcmp(key, "codec")) {
  107. av_log(s, AV_LOG_DEBUG, "Codec is <%s>\n", val);
  108. strncpy(codec_name, val, sizeof(codec_name) - 1);
  109. } else if (!strcmp(key, "HeaderSeed")) {
  110. av_log(s, AV_LOG_DEBUG, "HeaderSeed is <%s>\n", val);
  111. header_seed = atoi(val);
  112. } else if (!strcmp(key, "HeaderKey")) { // this looks like "1234567890 1234567890 1234567890 1234567890"
  113. av_log(s, AV_LOG_DEBUG, "HeaderKey is <%s>\n", val);
  114. ret = sscanf(val, "%"SCNu32"%"SCNu32"%"SCNu32"%"SCNu32,
  115. &header_key_part[0], &header_key_part[1], &header_key_part[2], &header_key_part[3]);
  116. if (ret != 4)
  117. return AVERROR_INVALIDDATA;
  118. for (idx = 0; idx < 4; idx++) {
  119. AV_WB32(&header_key[idx * 4], header_key_part[idx]); // convert each part to BE!
  120. }
  121. av_log(s, AV_LOG_DEBUG, "Processed HeaderKey is ");
  122. for (i = 0; i < 16; i++)
  123. av_log(s, AV_LOG_DEBUG, "%02x", header_key[i]);
  124. av_log(s, AV_LOG_DEBUG, "\n");
  125. } else {
  126. av_dict_set(&s->metadata, key, val, 0);
  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. /* verify codec */
  135. if ((c->codec_second_size = get_second_size(codec_name)) == -1) {
  136. av_log(s, AV_LOG_ERROR, "unknown codec <%s>!\n", codec_name);
  137. return AVERROR(EINVAL);
  138. }
  139. /* decryption key derivation */
  140. c->tea_ctx = av_tea_alloc();
  141. if (!c->tea_ctx)
  142. return AVERROR(ENOMEM);
  143. av_tea_init(c->tea_ctx, c->aa_fixed_key, 16);
  144. output[0] = output[1] = 0; // purely for padding purposes
  145. memcpy(output + 2, header_key, 16);
  146. idx = 0;
  147. for (i = 0; i < 3; i++) { // TEA CBC with weird mixed endianness
  148. AV_WB32(src, header_seed);
  149. AV_WB32(src + 4, header_seed + 1);
  150. header_seed += 2;
  151. av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 0); // TEA ECB encrypt
  152. for (j = 0; j < TEA_BLOCK_SIZE && idx < 18; j+=1, idx+=1) {
  153. output[idx] = output[idx] ^ dst[j];
  154. }
  155. }
  156. memcpy(c->file_key, output + 2, 16); // skip first 2 bytes of output
  157. av_log(s, AV_LOG_DEBUG, "File key is ");
  158. for (i = 0; i < 16; i++)
  159. av_log(s, AV_LOG_DEBUG, "%02x", c->file_key[i]);
  160. av_log(s, AV_LOG_DEBUG, "\n");
  161. /* decoder setup */
  162. st = avformat_new_stream(s, NULL);
  163. if (!st) {
  164. av_freep(&c->tea_ctx);
  165. return AVERROR(ENOMEM);
  166. }
  167. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  168. if (!strcmp(codec_name, "mp332")) {
  169. st->codecpar->codec_id = AV_CODEC_ID_MP3;
  170. st->codecpar->sample_rate = 22050;
  171. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  172. avpriv_set_pts_info(st, 64, 8, 32000 * TIMEPREC);
  173. // encoded audio frame is MP3_FRAME_SIZE bytes (+1 with padding, unlikely)
  174. } else if (!strcmp(codec_name, "acelp85")) {
  175. st->codecpar->codec_id = AV_CODEC_ID_SIPR;
  176. st->codecpar->block_align = 19;
  177. st->codecpar->channels = 1;
  178. st->codecpar->sample_rate = 8500;
  179. st->codecpar->bit_rate = 8500;
  180. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  181. avpriv_set_pts_info(st, 64, 8, 8500 * TIMEPREC);
  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->codecpar->bit_rate = 16000;
  188. st->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  189. avpriv_set_pts_info(st, 64, 8, 16000 * TIMEPREC);
  190. }
  191. /* determine, and jump to audio start offset */
  192. for (i = 1; i < toc_size; i++) { // skip the first entry!
  193. current_size = TOC[i].size;
  194. if (current_size > largest_size) {
  195. largest_idx = i;
  196. largest_size = current_size;
  197. }
  198. }
  199. start = TOC[largest_idx].offset;
  200. avio_seek(pb, start, SEEK_SET);
  201. // extract chapter positions. since all formats have constant bit rate, use it
  202. // as time base in bytes/s, for easy stream position <-> timestamp conversion
  203. st->start_time = 0;
  204. c->content_start = start;
  205. c->content_end = start + largest_size;
  206. while ((chapter_pos = avio_tell(pb)) >= 0 && chapter_pos < c->content_end) {
  207. int chapter_idx = s->nb_chapters;
  208. uint32_t chapter_size = avio_rb32(pb);
  209. if (chapter_size == 0 || avio_feof(pb))
  210. break;
  211. chapter_pos -= start + CHAPTER_HEADER_SIZE * chapter_idx;
  212. avio_skip(pb, 4 + chapter_size);
  213. if (!avpriv_new_chapter(s, chapter_idx, st->time_base,
  214. chapter_pos * TIMEPREC, (chapter_pos + chapter_size) * TIMEPREC, NULL))
  215. return AVERROR(ENOMEM);
  216. }
  217. st->duration = (largest_size - CHAPTER_HEADER_SIZE * s->nb_chapters) * TIMEPREC;
  218. ff_update_cur_dts(s, st, 0);
  219. avio_seek(pb, start, SEEK_SET);
  220. c->current_chapter_size = 0;
  221. c->seek_offset = 0;
  222. return 0;
  223. }
  224. static int aa_read_packet(AVFormatContext *s, AVPacket *pkt)
  225. {
  226. uint8_t dst[TEA_BLOCK_SIZE];
  227. uint8_t src[TEA_BLOCK_SIZE];
  228. int i;
  229. int trailing_bytes;
  230. int blocks;
  231. uint8_t buf[MAX_CODEC_SECOND_SIZE * 2];
  232. int written = 0;
  233. int ret;
  234. AADemuxContext *c = s->priv_data;
  235. uint64_t pos = avio_tell(s->pb);
  236. // are we at the end of the audio content?
  237. if (pos >= c->content_end) {
  238. return AVERROR_EOF;
  239. }
  240. // are we at the start of a chapter?
  241. if (c->current_chapter_size == 0) {
  242. c->current_chapter_size = avio_rb32(s->pb);
  243. if (c->current_chapter_size == 0) {
  244. return AVERROR_EOF;
  245. }
  246. av_log(s, AV_LOG_DEBUG, "Chapter %d (%" PRId64 " bytes)\n", c->chapter_idx, c->current_chapter_size);
  247. c->chapter_idx = c->chapter_idx + 1;
  248. avio_skip(s->pb, 4); // data start offset
  249. pos += 8;
  250. c->current_codec_second_size = c->codec_second_size;
  251. }
  252. // is this the last block in this chapter?
  253. if (c->current_chapter_size / c->current_codec_second_size == 0) {
  254. c->current_codec_second_size = c->current_chapter_size % c->current_codec_second_size;
  255. }
  256. // decrypt c->current_codec_second_size bytes
  257. blocks = c->current_codec_second_size / TEA_BLOCK_SIZE;
  258. for (i = 0; i < blocks; i++) {
  259. ret = avio_read(s->pb, src, TEA_BLOCK_SIZE);
  260. if (ret != TEA_BLOCK_SIZE)
  261. return (ret < 0) ? ret : AVERROR_EOF;
  262. av_tea_init(c->tea_ctx, c->file_key, 16);
  263. av_tea_crypt(c->tea_ctx, dst, src, 1, NULL, 1);
  264. memcpy(buf + written, dst, TEA_BLOCK_SIZE);
  265. written = written + TEA_BLOCK_SIZE;
  266. }
  267. trailing_bytes = c->current_codec_second_size % TEA_BLOCK_SIZE;
  268. if (trailing_bytes != 0) { // trailing bytes are left unencrypted!
  269. ret = avio_read(s->pb, src, trailing_bytes);
  270. if (ret != trailing_bytes)
  271. return (ret < 0) ? ret : AVERROR_EOF;
  272. memcpy(buf + written, src, trailing_bytes);
  273. written = written + trailing_bytes;
  274. }
  275. // update state
  276. c->current_chapter_size = c->current_chapter_size - c->current_codec_second_size;
  277. if (c->current_chapter_size <= 0)
  278. c->current_chapter_size = 0;
  279. if (c->seek_offset > written)
  280. c->seek_offset = 0; // ignore wrong estimate
  281. ret = av_new_packet(pkt, written - c->seek_offset);
  282. if (ret < 0)
  283. return ret;
  284. memcpy(pkt->data, buf + c->seek_offset, written - c->seek_offset);
  285. pkt->pos = pos;
  286. c->seek_offset = 0;
  287. return 0;
  288. }
  289. static int aa_read_seek(AVFormatContext *s,
  290. int stream_index, int64_t timestamp, int flags)
  291. {
  292. AADemuxContext *c = s->priv_data;
  293. AVChapter *ch;
  294. int64_t chapter_pos, chapter_start, chapter_size;
  295. int chapter_idx = 0;
  296. // find chapter containing seek timestamp
  297. if (timestamp < 0)
  298. timestamp = 0;
  299. while (chapter_idx < s->nb_chapters && timestamp >= s->chapters[chapter_idx]->end) {
  300. ++chapter_idx;
  301. }
  302. if (chapter_idx >= s->nb_chapters) {
  303. chapter_idx = s->nb_chapters - 1;
  304. if (chapter_idx < 0) return -1; // there is no chapter.
  305. timestamp = s->chapters[chapter_idx]->end;
  306. }
  307. ch = s->chapters[chapter_idx];
  308. // sync by clamping timestamp to nearest valid block position in its chapter
  309. chapter_size = ch->end / TIMEPREC - ch->start / TIMEPREC;
  310. chapter_pos = av_rescale_rnd((timestamp - ch->start) / TIMEPREC,
  311. 1, c->codec_second_size,
  312. (flags & AVSEEK_FLAG_BACKWARD) ? AV_ROUND_DOWN : AV_ROUND_UP)
  313. * c->codec_second_size;
  314. if (chapter_pos >= chapter_size)
  315. chapter_pos = chapter_size;
  316. chapter_start = c->content_start + (ch->start / TIMEPREC) + CHAPTER_HEADER_SIZE * (1 + chapter_idx);
  317. // reinit read state
  318. avio_seek(s->pb, chapter_start + chapter_pos, SEEK_SET);
  319. c->current_codec_second_size = c->codec_second_size;
  320. c->current_chapter_size = chapter_size - chapter_pos;
  321. c->chapter_idx = 1 + chapter_idx;
  322. // for unaligned frames, estimate offset of first frame in block (assume no padding)
  323. if (s->streams[0]->codecpar->codec_id == AV_CODEC_ID_MP3) {
  324. c->seek_offset = (MP3_FRAME_SIZE - chapter_pos % MP3_FRAME_SIZE) % MP3_FRAME_SIZE;
  325. }
  326. ff_update_cur_dts(s, s->streams[0], ch->start + (chapter_pos + c->seek_offset) * TIMEPREC);
  327. return 1;
  328. }
  329. static int aa_probe(const AVProbeData *p)
  330. {
  331. uint8_t *buf = p->buf;
  332. // first 4 bytes are file size, next 4 bytes are the magic
  333. if (AV_RB32(buf+4) != AA_MAGIC)
  334. return 0;
  335. return AVPROBE_SCORE_MAX / 2;
  336. }
  337. static int aa_read_close(AVFormatContext *s)
  338. {
  339. AADemuxContext *c = s->priv_data;
  340. av_freep(&c->tea_ctx);
  341. return 0;
  342. }
  343. #define OFFSET(x) offsetof(AADemuxContext, x)
  344. static const AVOption aa_options[] = {
  345. { "aa_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files!
  346. "Fixed key used for handling Audible AA files", OFFSET(aa_fixed_key),
  347. AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd2a51d673"},
  348. .flags = AV_OPT_FLAG_DECODING_PARAM },
  349. { NULL },
  350. };
  351. static const AVClass aa_class = {
  352. .class_name = "aa",
  353. .item_name = av_default_item_name,
  354. .option = aa_options,
  355. .version = LIBAVUTIL_VERSION_INT,
  356. };
  357. AVInputFormat ff_aa_demuxer = {
  358. .name = "aa",
  359. .long_name = NULL_IF_CONFIG_SMALL("Audible AA format files"),
  360. .priv_class = &aa_class,
  361. .priv_data_size = sizeof(AADemuxContext),
  362. .extensions = "aa",
  363. .read_probe = aa_probe,
  364. .read_header = aa_read_header,
  365. .read_packet = aa_read_packet,
  366. .read_seek = aa_read_seek,
  367. .read_close = aa_read_close,
  368. .flags = AVFMT_NO_BYTE_SEEK | AVFMT_NOGENSEARCH,
  369. };