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.

465 lines
17KB

  1. /*
  2. * Monkey's Audio APE demuxer
  3. * Copyright (c) 2007 Benjamin Zores <ben@geexbox.org>
  4. * based upon libdemac from Dave Chapman.
  5. *
  6. * This file is part of Libav.
  7. *
  8. * Libav is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * Libav is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with Libav; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include <stdio.h>
  23. #include "libavutil/intreadwrite.h"
  24. #include "avformat.h"
  25. #include "internal.h"
  26. #include "apetag.h"
  27. /* The earliest and latest file formats supported by this library */
  28. #define APE_MIN_VERSION 3800
  29. #define APE_MAX_VERSION 3990
  30. #define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE]
  31. #define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE]
  32. #define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE]
  33. #define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE]
  34. #define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level
  35. #define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored)
  36. #define MAC_SUBFRAME_SIZE 4608
  37. #define APE_EXTRADATA_SIZE 6
  38. typedef struct APEFrame {
  39. int64_t pos;
  40. int nblocks;
  41. int size;
  42. int skip;
  43. int64_t pts;
  44. } APEFrame;
  45. typedef struct APEContext {
  46. /* Derived fields */
  47. uint32_t junklength;
  48. uint32_t firstframe;
  49. uint32_t totalsamples;
  50. int currentframe;
  51. APEFrame *frames;
  52. /* Info from Descriptor Block */
  53. char magic[4];
  54. int16_t fileversion;
  55. int16_t padding1;
  56. uint32_t descriptorlength;
  57. uint32_t headerlength;
  58. uint32_t seektablelength;
  59. uint32_t wavheaderlength;
  60. uint32_t audiodatalength;
  61. uint32_t audiodatalength_high;
  62. uint32_t wavtaillength;
  63. uint8_t md5[16];
  64. /* Info from Header Block */
  65. uint16_t compressiontype;
  66. uint16_t formatflags;
  67. uint32_t blocksperframe;
  68. uint32_t finalframeblocks;
  69. uint32_t totalframes;
  70. uint16_t bps;
  71. uint16_t channels;
  72. uint32_t samplerate;
  73. /* Seektable */
  74. uint32_t *seektable;
  75. uint8_t *bittable;
  76. } APEContext;
  77. static int ape_probe(AVProbeData * p)
  78. {
  79. if (p->buf[0] == 'M' && p->buf[1] == 'A' && p->buf[2] == 'C' && p->buf[3] == ' ')
  80. return AVPROBE_SCORE_MAX;
  81. return 0;
  82. }
  83. static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx)
  84. {
  85. #ifdef DEBUG
  86. int i;
  87. av_log(s, AV_LOG_DEBUG, "Descriptor Block:\n\n");
  88. av_log(s, AV_LOG_DEBUG, "magic = \"%c%c%c%c\"\n", ape_ctx->magic[0], ape_ctx->magic[1], ape_ctx->magic[2], ape_ctx->magic[3]);
  89. av_log(s, AV_LOG_DEBUG, "fileversion = %"PRId16"\n", ape_ctx->fileversion);
  90. av_log(s, AV_LOG_DEBUG, "descriptorlength = %"PRIu32"\n", ape_ctx->descriptorlength);
  91. av_log(s, AV_LOG_DEBUG, "headerlength = %"PRIu32"\n", ape_ctx->headerlength);
  92. av_log(s, AV_LOG_DEBUG, "seektablelength = %"PRIu32"\n", ape_ctx->seektablelength);
  93. av_log(s, AV_LOG_DEBUG, "wavheaderlength = %"PRIu32"\n", ape_ctx->wavheaderlength);
  94. av_log(s, AV_LOG_DEBUG, "audiodatalength = %"PRIu32"\n", ape_ctx->audiodatalength);
  95. av_log(s, AV_LOG_DEBUG, "audiodatalength_high = %"PRIu32"\n", ape_ctx->audiodatalength_high);
  96. av_log(s, AV_LOG_DEBUG, "wavtaillength = %"PRIu32"\n", ape_ctx->wavtaillength);
  97. av_log(s, AV_LOG_DEBUG, "md5 = ");
  98. for (i = 0; i < 16; i++)
  99. av_log(s, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
  100. av_log(s, AV_LOG_DEBUG, "\n");
  101. av_log(s, AV_LOG_DEBUG, "\nHeader Block:\n\n");
  102. av_log(s, AV_LOG_DEBUG, "compressiontype = %"PRIu16"\n", ape_ctx->compressiontype);
  103. av_log(s, AV_LOG_DEBUG, "formatflags = %"PRIu16"\n", ape_ctx->formatflags);
  104. av_log(s, AV_LOG_DEBUG, "blocksperframe = %"PRIu32"\n", ape_ctx->blocksperframe);
  105. av_log(s, AV_LOG_DEBUG, "finalframeblocks = %"PRIu32"\n", ape_ctx->finalframeblocks);
  106. av_log(s, AV_LOG_DEBUG, "totalframes = %"PRIu32"\n", ape_ctx->totalframes);
  107. av_log(s, AV_LOG_DEBUG, "bps = %"PRIu16"\n", ape_ctx->bps);
  108. av_log(s, AV_LOG_DEBUG, "channels = %"PRIu16"\n", ape_ctx->channels);
  109. av_log(s, AV_LOG_DEBUG, "samplerate = %"PRIu32"\n", ape_ctx->samplerate);
  110. av_log(s, AV_LOG_DEBUG, "\nSeektable\n\n");
  111. if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
  112. av_log(s, AV_LOG_DEBUG, "No seektable\n");
  113. } else {
  114. for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) {
  115. if (i < ape_ctx->totalframes - 1) {
  116. av_log(s, AV_LOG_DEBUG, "%8d %"PRIu32" (%"PRIu32" bytes)",
  117. i, ape_ctx->seektable[i],
  118. ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]);
  119. if (ape_ctx->bittable)
  120. av_log(s, AV_LOG_DEBUG, " + %2d bits\n",
  121. ape_ctx->bittable[i]);
  122. av_log(s, AV_LOG_DEBUG, "\n");
  123. } else {
  124. av_log(s, AV_LOG_DEBUG, "%8d %"PRIu32"\n", i, ape_ctx->seektable[i]);
  125. }
  126. }
  127. }
  128. av_log(s, AV_LOG_DEBUG, "\nFrames\n\n");
  129. for (i = 0; i < ape_ctx->totalframes; i++)
  130. av_log(s, AV_LOG_DEBUG, "%8d %8"PRId64" %8d (%d samples)\n", i,
  131. ape_ctx->frames[i].pos, ape_ctx->frames[i].size,
  132. ape_ctx->frames[i].nblocks);
  133. av_log(s, AV_LOG_DEBUG, "\nCalculated information:\n\n");
  134. av_log(s, AV_LOG_DEBUG, "junklength = %"PRIu32"\n", ape_ctx->junklength);
  135. av_log(s, AV_LOG_DEBUG, "firstframe = %"PRIu32"\n", ape_ctx->firstframe);
  136. av_log(s, AV_LOG_DEBUG, "totalsamples = %"PRIu32"\n", ape_ctx->totalsamples);
  137. #endif
  138. }
  139. static int ape_read_header(AVFormatContext * s)
  140. {
  141. AVIOContext *pb = s->pb;
  142. APEContext *ape = s->priv_data;
  143. AVStream *st;
  144. uint32_t tag;
  145. int i;
  146. int total_blocks, final_size = 0;
  147. int64_t pts, file_size;
  148. /* Skip any leading junk such as id3v2 tags */
  149. ape->junklength = avio_tell(pb);
  150. tag = avio_rl32(pb);
  151. if (tag != MKTAG('M', 'A', 'C', ' '))
  152. return -1;
  153. ape->fileversion = avio_rl16(pb);
  154. if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
  155. av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n",
  156. ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
  157. return -1;
  158. }
  159. if (ape->fileversion >= 3980) {
  160. ape->padding1 = avio_rl16(pb);
  161. ape->descriptorlength = avio_rl32(pb);
  162. ape->headerlength = avio_rl32(pb);
  163. ape->seektablelength = avio_rl32(pb);
  164. ape->wavheaderlength = avio_rl32(pb);
  165. ape->audiodatalength = avio_rl32(pb);
  166. ape->audiodatalength_high = avio_rl32(pb);
  167. ape->wavtaillength = avio_rl32(pb);
  168. avio_read(pb, ape->md5, 16);
  169. /* Skip any unknown bytes at the end of the descriptor.
  170. This is for future compatibility */
  171. if (ape->descriptorlength > 52)
  172. avio_skip(pb, ape->descriptorlength - 52);
  173. /* Read header data */
  174. ape->compressiontype = avio_rl16(pb);
  175. ape->formatflags = avio_rl16(pb);
  176. ape->blocksperframe = avio_rl32(pb);
  177. ape->finalframeblocks = avio_rl32(pb);
  178. ape->totalframes = avio_rl32(pb);
  179. ape->bps = avio_rl16(pb);
  180. ape->channels = avio_rl16(pb);
  181. ape->samplerate = avio_rl32(pb);
  182. } else {
  183. ape->descriptorlength = 0;
  184. ape->headerlength = 32;
  185. ape->compressiontype = avio_rl16(pb);
  186. ape->formatflags = avio_rl16(pb);
  187. ape->channels = avio_rl16(pb);
  188. ape->samplerate = avio_rl32(pb);
  189. ape->wavheaderlength = avio_rl32(pb);
  190. ape->wavtaillength = avio_rl32(pb);
  191. ape->totalframes = avio_rl32(pb);
  192. ape->finalframeblocks = avio_rl32(pb);
  193. if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
  194. avio_skip(pb, 4); /* Skip the peak level */
  195. ape->headerlength += 4;
  196. }
  197. if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
  198. ape->seektablelength = avio_rl32(pb);
  199. ape->headerlength += 4;
  200. ape->seektablelength *= sizeof(int32_t);
  201. } else
  202. ape->seektablelength = ape->totalframes * sizeof(int32_t);
  203. if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
  204. ape->bps = 8;
  205. else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
  206. ape->bps = 24;
  207. else
  208. ape->bps = 16;
  209. if (ape->fileversion >= 3950)
  210. ape->blocksperframe = 73728 * 4;
  211. else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
  212. ape->blocksperframe = 73728;
  213. else
  214. ape->blocksperframe = 9216;
  215. /* Skip any stored wav header */
  216. if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
  217. avio_skip(pb, ape->wavheaderlength);
  218. }
  219. if(!ape->totalframes){
  220. av_log(s, AV_LOG_ERROR, "No frames in the file!\n");
  221. return AVERROR(EINVAL);
  222. }
  223. if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
  224. av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n",
  225. ape->totalframes);
  226. return -1;
  227. }
  228. if (ape->seektablelength / sizeof(*ape->seektable) < ape->totalframes) {
  229. av_log(s, AV_LOG_ERROR,
  230. "Number of seek entries is less than number of frames: %zu vs. %"PRIu32"\n",
  231. ape->seektablelength / sizeof(*ape->seektable), ape->totalframes);
  232. return AVERROR_INVALIDDATA;
  233. }
  234. ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame));
  235. if(!ape->frames)
  236. return AVERROR(ENOMEM);
  237. ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
  238. if (ape->fileversion < 3810)
  239. ape->firstframe += ape->totalframes;
  240. ape->currentframe = 0;
  241. ape->totalsamples = ape->finalframeblocks;
  242. if (ape->totalframes > 1)
  243. ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
  244. if (ape->seektablelength > 0) {
  245. ape->seektable = av_malloc(ape->seektablelength);
  246. if (!ape->seektable)
  247. return AVERROR(ENOMEM);
  248. for (i = 0; i < ape->seektablelength / sizeof(uint32_t) && !pb->eof_reached; i++)
  249. ape->seektable[i] = avio_rl32(pb);
  250. if (ape->fileversion < 3810) {
  251. ape->bittable = av_malloc(ape->totalframes);
  252. if (!ape->bittable)
  253. return AVERROR(ENOMEM);
  254. for (i = 0; i < ape->totalframes && !pb->eof_reached; i++)
  255. ape->bittable[i] = avio_r8(pb);
  256. }
  257. }
  258. ape->frames[0].pos = ape->firstframe;
  259. ape->frames[0].nblocks = ape->blocksperframe;
  260. ape->frames[0].skip = 0;
  261. for (i = 1; i < ape->totalframes; i++) {
  262. ape->frames[i].pos = ape->seektable[i] + ape->junklength;
  263. ape->frames[i].nblocks = ape->blocksperframe;
  264. ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
  265. ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
  266. }
  267. ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
  268. /* calculate final packet size from total file size, if available */
  269. file_size = avio_size(pb);
  270. if (file_size > 0) {
  271. final_size = file_size - ape->frames[ape->totalframes - 1].pos -
  272. ape->wavtaillength;
  273. final_size -= final_size & 3;
  274. }
  275. if (file_size <= 0 || final_size <= 0)
  276. final_size = ape->finalframeblocks * 8;
  277. ape->frames[ape->totalframes - 1].size = final_size;
  278. for (i = 0; i < ape->totalframes; i++) {
  279. if(ape->frames[i].skip){
  280. ape->frames[i].pos -= ape->frames[i].skip;
  281. ape->frames[i].size += ape->frames[i].skip;
  282. }
  283. ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
  284. }
  285. if (ape->fileversion < 3810) {
  286. for (i = 0; i < ape->totalframes; i++) {
  287. if (i < ape->totalframes - 1 && ape->bittable[i + 1])
  288. ape->frames[i].size += 4;
  289. ape->frames[i].skip <<= 3;
  290. ape->frames[i].skip += ape->bittable[i];
  291. }
  292. }
  293. ape_dumpinfo(s, ape);
  294. av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %"PRIu16"\n",
  295. ape->fileversion / 1000, (ape->fileversion % 1000) / 10,
  296. ape->compressiontype);
  297. /* now we are ready: build format streams */
  298. st = avformat_new_stream(s, NULL);
  299. if (!st)
  300. return -1;
  301. total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
  302. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  303. st->codec->codec_id = AV_CODEC_ID_APE;
  304. st->codec->codec_tag = MKTAG('A', 'P', 'E', ' ');
  305. st->codec->channels = ape->channels;
  306. st->codec->sample_rate = ape->samplerate;
  307. st->codec->bits_per_coded_sample = ape->bps;
  308. st->nb_frames = ape->totalframes;
  309. st->start_time = 0;
  310. st->duration = total_blocks / MAC_SUBFRAME_SIZE;
  311. avpriv_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);
  312. st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE);
  313. st->codec->extradata_size = APE_EXTRADATA_SIZE;
  314. AV_WL16(st->codec->extradata + 0, ape->fileversion);
  315. AV_WL16(st->codec->extradata + 2, ape->compressiontype);
  316. AV_WL16(st->codec->extradata + 4, ape->formatflags);
  317. pts = 0;
  318. for (i = 0; i < ape->totalframes; i++) {
  319. ape->frames[i].pts = pts;
  320. av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
  321. pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;
  322. }
  323. /* try to read APE tags */
  324. if (pb->seekable) {
  325. ff_ape_parse_tag(s);
  326. avio_seek(pb, 0, SEEK_SET);
  327. }
  328. return 0;
  329. }
  330. static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
  331. {
  332. int ret;
  333. int nblocks;
  334. APEContext *ape = s->priv_data;
  335. uint32_t extra_size = 8;
  336. if (s->pb->eof_reached)
  337. return AVERROR_EOF;
  338. if (ape->currentframe >= ape->totalframes)
  339. return AVERROR_EOF;
  340. if (avio_seek(s->pb, ape->frames[ape->currentframe].pos, SEEK_SET) < 0)
  341. return AVERROR(EIO);
  342. /* Calculate how many blocks there are in this frame */
  343. if (ape->currentframe == (ape->totalframes - 1))
  344. nblocks = ape->finalframeblocks;
  345. else
  346. nblocks = ape->blocksperframe;
  347. if (ape->frames[ape->currentframe].size <= 0 ||
  348. ape->frames[ape->currentframe].size > INT_MAX - extra_size) {
  349. av_log(s, AV_LOG_ERROR, "invalid packet size: %d\n",
  350. ape->frames[ape->currentframe].size);
  351. ape->currentframe++;
  352. return AVERROR(EIO);
  353. }
  354. if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0)
  355. return AVERROR(ENOMEM);
  356. AV_WL32(pkt->data , nblocks);
  357. AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
  358. ret = avio_read(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
  359. pkt->pts = ape->frames[ape->currentframe].pts;
  360. pkt->stream_index = 0;
  361. /* note: we need to modify the packet size here to handle the last
  362. packet */
  363. pkt->size = ret + extra_size;
  364. ape->currentframe++;
  365. return 0;
  366. }
  367. static int ape_read_close(AVFormatContext * s)
  368. {
  369. APEContext *ape = s->priv_data;
  370. av_freep(&ape->frames);
  371. av_freep(&ape->seektable);
  372. av_freep(&ape->bittable);
  373. return 0;
  374. }
  375. static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  376. {
  377. AVStream *st = s->streams[stream_index];
  378. APEContext *ape = s->priv_data;
  379. int index = av_index_search_timestamp(st, timestamp, flags);
  380. if (index < 0)
  381. return -1;
  382. if (avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET) < 0)
  383. return -1;
  384. ape->currentframe = index;
  385. return 0;
  386. }
  387. AVInputFormat ff_ape_demuxer = {
  388. .name = "ape",
  389. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  390. .priv_data_size = sizeof(APEContext),
  391. .read_probe = ape_probe,
  392. .read_header = ape_read_header,
  393. .read_packet = ape_read_packet,
  394. .read_close = ape_read_close,
  395. .read_seek = ape_read_seek,
  396. .extensions = "ape,apl,mac",
  397. };