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.

473 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 FFmpeg.
  7. *
  8. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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 APE_EXTRADATA_SIZE 6
  37. typedef struct {
  38. int64_t pos;
  39. int nblocks;
  40. int size;
  41. int skip;
  42. int64_t pts;
  43. } APEFrame;
  44. typedef struct {
  45. /* Derived fields */
  46. uint32_t junklength;
  47. uint32_t firstframe;
  48. uint32_t totalsamples;
  49. int currentframe;
  50. APEFrame *frames;
  51. /* Info from Descriptor Block */
  52. char magic[4];
  53. int16_t fileversion;
  54. int16_t padding1;
  55. uint32_t descriptorlength;
  56. uint32_t headerlength;
  57. uint32_t seektablelength;
  58. uint32_t wavheaderlength;
  59. uint32_t audiodatalength;
  60. uint32_t audiodatalength_high;
  61. uint32_t wavtaillength;
  62. uint8_t md5[16];
  63. /* Info from Header Block */
  64. uint16_t compressiontype;
  65. uint16_t formatflags;
  66. uint32_t blocksperframe;
  67. uint32_t finalframeblocks;
  68. uint32_t totalframes;
  69. uint16_t bps;
  70. uint16_t channels;
  71. uint32_t samplerate;
  72. /* Seektable */
  73. uint32_t *seektable;
  74. uint8_t *bittable;
  75. } APEContext;
  76. static int ape_probe(AVProbeData * p)
  77. {
  78. int version = AV_RL16(p->buf+4);
  79. if (AV_RL32(p->buf) != MKTAG('M', 'A', 'C', ' '))
  80. return 0;
  81. if (version < APE_MIN_VERSION || version > APE_MAX_VERSION)
  82. return AVPROBE_SCORE_MAX/4;
  83. return AVPROBE_SCORE_MAX;
  84. }
  85. static void ape_dumpinfo(AVFormatContext * s, APEContext * ape_ctx)
  86. {
  87. #ifdef DEBUG
  88. int i;
  89. av_log(s, AV_LOG_DEBUG, "Descriptor Block:\n\n");
  90. 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]);
  91. av_log(s, AV_LOG_DEBUG, "fileversion = %"PRId16"\n", ape_ctx->fileversion);
  92. av_log(s, AV_LOG_DEBUG, "descriptorlength = %"PRIu32"\n", ape_ctx->descriptorlength);
  93. av_log(s, AV_LOG_DEBUG, "headerlength = %"PRIu32"\n", ape_ctx->headerlength);
  94. av_log(s, AV_LOG_DEBUG, "seektablelength = %"PRIu32"\n", ape_ctx->seektablelength);
  95. av_log(s, AV_LOG_DEBUG, "wavheaderlength = %"PRIu32"\n", ape_ctx->wavheaderlength);
  96. av_log(s, AV_LOG_DEBUG, "audiodatalength = %"PRIu32"\n", ape_ctx->audiodatalength);
  97. av_log(s, AV_LOG_DEBUG, "audiodatalength_high = %"PRIu32"\n", ape_ctx->audiodatalength_high);
  98. av_log(s, AV_LOG_DEBUG, "wavtaillength = %"PRIu32"\n", ape_ctx->wavtaillength);
  99. av_log(s, AV_LOG_DEBUG, "md5 = ");
  100. for (i = 0; i < 16; i++)
  101. av_log(s, AV_LOG_DEBUG, "%02x", ape_ctx->md5[i]);
  102. av_log(s, AV_LOG_DEBUG, "\n");
  103. av_log(s, AV_LOG_DEBUG, "\nHeader Block:\n\n");
  104. av_log(s, AV_LOG_DEBUG, "compressiontype = %"PRIu16"\n", ape_ctx->compressiontype);
  105. av_log(s, AV_LOG_DEBUG, "formatflags = %"PRIu16"\n", ape_ctx->formatflags);
  106. av_log(s, AV_LOG_DEBUG, "blocksperframe = %"PRIu32"\n", ape_ctx->blocksperframe);
  107. av_log(s, AV_LOG_DEBUG, "finalframeblocks = %"PRIu32"\n", ape_ctx->finalframeblocks);
  108. av_log(s, AV_LOG_DEBUG, "totalframes = %"PRIu32"\n", ape_ctx->totalframes);
  109. av_log(s, AV_LOG_DEBUG, "bps = %"PRIu16"\n", ape_ctx->bps);
  110. av_log(s, AV_LOG_DEBUG, "channels = %"PRIu16"\n", ape_ctx->channels);
  111. av_log(s, AV_LOG_DEBUG, "samplerate = %"PRIu32"\n", ape_ctx->samplerate);
  112. av_log(s, AV_LOG_DEBUG, "\nSeektable\n\n");
  113. if ((ape_ctx->seektablelength / sizeof(uint32_t)) != ape_ctx->totalframes) {
  114. av_log(s, AV_LOG_DEBUG, "No seektable\n");
  115. } else {
  116. for (i = 0; i < ape_ctx->seektablelength / sizeof(uint32_t); i++) {
  117. if (i < ape_ctx->totalframes - 1) {
  118. av_log(s, AV_LOG_DEBUG, "%8d %"PRIu32" (%"PRIu32" bytes)",
  119. i, ape_ctx->seektable[i],
  120. ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]);
  121. if (ape_ctx->bittable)
  122. av_log(s, AV_LOG_DEBUG, " + %2d bits\n",
  123. ape_ctx->bittable[i]);
  124. av_log(s, AV_LOG_DEBUG, "\n");
  125. } else {
  126. av_log(s, AV_LOG_DEBUG, "%8d %"PRIu32"\n", i, ape_ctx->seektable[i]);
  127. }
  128. }
  129. }
  130. av_log(s, AV_LOG_DEBUG, "\nFrames\n\n");
  131. for (i = 0; i < ape_ctx->totalframes; i++)
  132. av_log(s, AV_LOG_DEBUG, "%8d %8"PRId64" %8d (%d samples)\n", i,
  133. ape_ctx->frames[i].pos, ape_ctx->frames[i].size,
  134. ape_ctx->frames[i].nblocks);
  135. av_log(s, AV_LOG_DEBUG, "\nCalculated information:\n\n");
  136. av_log(s, AV_LOG_DEBUG, "junklength = %"PRIu32"\n", ape_ctx->junklength);
  137. av_log(s, AV_LOG_DEBUG, "firstframe = %"PRIu32"\n", ape_ctx->firstframe);
  138. av_log(s, AV_LOG_DEBUG, "totalsamples = %"PRIu32"\n", ape_ctx->totalsamples);
  139. #endif
  140. }
  141. static int ape_read_header(AVFormatContext * s)
  142. {
  143. AVIOContext *pb = s->pb;
  144. APEContext *ape = s->priv_data;
  145. AVStream *st;
  146. uint32_t tag;
  147. int i;
  148. int total_blocks, final_size = 0;
  149. int64_t pts, file_size;
  150. /* Skip any leading junk such as id3v2 tags */
  151. ape->junklength = avio_tell(pb);
  152. tag = avio_rl32(pb);
  153. if (tag != MKTAG('M', 'A', 'C', ' '))
  154. return AVERROR_INVALIDDATA;
  155. ape->fileversion = avio_rl16(pb);
  156. if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
  157. av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n",
  158. ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
  159. return AVERROR_PATCHWELCOME;
  160. }
  161. if (ape->fileversion >= 3980) {
  162. ape->padding1 = avio_rl16(pb);
  163. ape->descriptorlength = avio_rl32(pb);
  164. ape->headerlength = avio_rl32(pb);
  165. ape->seektablelength = avio_rl32(pb);
  166. ape->wavheaderlength = avio_rl32(pb);
  167. ape->audiodatalength = avio_rl32(pb);
  168. ape->audiodatalength_high = avio_rl32(pb);
  169. ape->wavtaillength = avio_rl32(pb);
  170. avio_read(pb, ape->md5, 16);
  171. /* Skip any unknown bytes at the end of the descriptor.
  172. This is for future compatibility */
  173. if (ape->descriptorlength > 52)
  174. avio_skip(pb, ape->descriptorlength - 52);
  175. /* Read header data */
  176. ape->compressiontype = avio_rl16(pb);
  177. ape->formatflags = avio_rl16(pb);
  178. ape->blocksperframe = avio_rl32(pb);
  179. ape->finalframeblocks = avio_rl32(pb);
  180. ape->totalframes = avio_rl32(pb);
  181. ape->bps = avio_rl16(pb);
  182. ape->channels = avio_rl16(pb);
  183. ape->samplerate = avio_rl32(pb);
  184. } else {
  185. ape->descriptorlength = 0;
  186. ape->headerlength = 32;
  187. ape->compressiontype = avio_rl16(pb);
  188. ape->formatflags = avio_rl16(pb);
  189. ape->channels = avio_rl16(pb);
  190. ape->samplerate = avio_rl32(pb);
  191. ape->wavheaderlength = avio_rl32(pb);
  192. ape->wavtaillength = avio_rl32(pb);
  193. ape->totalframes = avio_rl32(pb);
  194. ape->finalframeblocks = avio_rl32(pb);
  195. if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
  196. avio_skip(pb, 4); /* Skip the peak level */
  197. ape->headerlength += 4;
  198. }
  199. if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
  200. ape->seektablelength = avio_rl32(pb);
  201. ape->headerlength += 4;
  202. ape->seektablelength *= sizeof(int32_t);
  203. } else
  204. ape->seektablelength = ape->totalframes * sizeof(int32_t);
  205. if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
  206. ape->bps = 8;
  207. else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
  208. ape->bps = 24;
  209. else
  210. ape->bps = 16;
  211. if (ape->fileversion >= 3950)
  212. ape->blocksperframe = 73728 * 4;
  213. else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
  214. ape->blocksperframe = 73728;
  215. else
  216. ape->blocksperframe = 9216;
  217. /* Skip any stored wav header */
  218. if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
  219. avio_skip(pb, ape->wavheaderlength);
  220. }
  221. if(!ape->totalframes){
  222. av_log(s, AV_LOG_ERROR, "No frames in the file!\n");
  223. return AVERROR(EINVAL);
  224. }
  225. if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
  226. av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n",
  227. ape->totalframes);
  228. return AVERROR_INVALIDDATA;
  229. }
  230. if (ape->seektablelength / sizeof(*ape->seektable) < ape->totalframes) {
  231. av_log(s, AV_LOG_ERROR,
  232. "Number of seek entries is less than number of frames: %"SIZE_SPECIFIER" vs. %"PRIu32"\n",
  233. ape->seektablelength / sizeof(*ape->seektable), ape->totalframes);
  234. return AVERROR_INVALIDDATA;
  235. }
  236. ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame));
  237. if(!ape->frames)
  238. return AVERROR(ENOMEM);
  239. ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
  240. if (ape->fileversion < 3810)
  241. ape->firstframe += ape->totalframes;
  242. ape->currentframe = 0;
  243. ape->totalsamples = ape->finalframeblocks;
  244. if (ape->totalframes > 1)
  245. ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
  246. if (ape->seektablelength > 0) {
  247. ape->seektable = av_mallocz(ape->seektablelength);
  248. if (!ape->seektable)
  249. return AVERROR(ENOMEM);
  250. for (i = 0; i < ape->seektablelength / sizeof(uint32_t) && !pb->eof_reached; i++)
  251. ape->seektable[i] = avio_rl32(pb);
  252. if (ape->fileversion < 3810) {
  253. ape->bittable = av_mallocz(ape->totalframes);
  254. if (!ape->bittable)
  255. return AVERROR(ENOMEM);
  256. for (i = 0; i < ape->totalframes && !pb->eof_reached; i++)
  257. ape->bittable[i] = avio_r8(pb);
  258. }
  259. if (pb->eof_reached)
  260. av_log(s, AV_LOG_WARNING, "File truncated\n");
  261. }
  262. ape->frames[0].pos = ape->firstframe;
  263. ape->frames[0].nblocks = ape->blocksperframe;
  264. ape->frames[0].skip = 0;
  265. for (i = 1; i < ape->totalframes; i++) {
  266. ape->frames[i].pos = ape->seektable[i] + ape->junklength;
  267. ape->frames[i].nblocks = ape->blocksperframe;
  268. ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
  269. ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
  270. }
  271. ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
  272. /* calculate final packet size from total file size, if available */
  273. file_size = avio_size(pb);
  274. if (file_size > 0) {
  275. final_size = file_size - ape->frames[ape->totalframes - 1].pos -
  276. ape->wavtaillength;
  277. final_size -= final_size & 3;
  278. }
  279. if (file_size <= 0 || final_size <= 0)
  280. final_size = ape->finalframeblocks * 8;
  281. ape->frames[ape->totalframes - 1].size = final_size;
  282. for (i = 0; i < ape->totalframes; i++) {
  283. if(ape->frames[i].skip){
  284. ape->frames[i].pos -= ape->frames[i].skip;
  285. ape->frames[i].size += ape->frames[i].skip;
  286. }
  287. ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
  288. }
  289. if (ape->fileversion < 3810) {
  290. for (i = 0; i < ape->totalframes; i++) {
  291. if (i < ape->totalframes - 1 && ape->bittable[i + 1])
  292. ape->frames[i].size += 4;
  293. ape->frames[i].skip <<= 3;
  294. ape->frames[i].skip += ape->bittable[i];
  295. }
  296. }
  297. ape_dumpinfo(s, ape);
  298. av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %"PRIu16"\n",
  299. ape->fileversion / 1000, (ape->fileversion % 1000) / 10,
  300. ape->compressiontype);
  301. /* now we are ready: build format streams */
  302. st = avformat_new_stream(s, NULL);
  303. if (!st)
  304. return AVERROR(ENOMEM);
  305. total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
  306. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  307. st->codec->codec_id = AV_CODEC_ID_APE;
  308. st->codec->codec_tag = MKTAG('A', 'P', 'E', ' ');
  309. st->codec->channels = ape->channels;
  310. st->codec->sample_rate = ape->samplerate;
  311. st->codec->bits_per_coded_sample = ape->bps;
  312. st->nb_frames = ape->totalframes;
  313. st->start_time = 0;
  314. st->duration = total_blocks;
  315. avpriv_set_pts_info(st, 64, 1, ape->samplerate);
  316. if (ff_alloc_extradata(st->codec, APE_EXTRADATA_SIZE))
  317. return AVERROR(ENOMEM);
  318. AV_WL16(st->codec->extradata + 0, ape->fileversion);
  319. AV_WL16(st->codec->extradata + 2, ape->compressiontype);
  320. AV_WL16(st->codec->extradata + 4, ape->formatflags);
  321. pts = 0;
  322. for (i = 0; i < ape->totalframes; i++) {
  323. ape->frames[i].pts = pts;
  324. av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
  325. pts += ape->blocksperframe;
  326. }
  327. /* try to read APE tags */
  328. if (pb->seekable) {
  329. ff_ape_parse_tag(s);
  330. avio_seek(pb, 0, SEEK_SET);
  331. }
  332. return 0;
  333. }
  334. static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
  335. {
  336. int ret;
  337. int nblocks;
  338. APEContext *ape = s->priv_data;
  339. uint32_t extra_size = 8;
  340. if (url_feof(s->pb))
  341. return AVERROR_EOF;
  342. if (ape->currentframe >= ape->totalframes)
  343. return AVERROR_EOF;
  344. if (avio_seek(s->pb, ape->frames[ape->currentframe].pos, SEEK_SET) < 0)
  345. return AVERROR(EIO);
  346. /* Calculate how many blocks there are in this frame */
  347. if (ape->currentframe == (ape->totalframes - 1))
  348. nblocks = ape->finalframeblocks;
  349. else
  350. nblocks = ape->blocksperframe;
  351. if (ape->frames[ape->currentframe].size <= 0 ||
  352. ape->frames[ape->currentframe].size > INT_MAX - extra_size) {
  353. av_log(s, AV_LOG_ERROR, "invalid packet size: %d\n",
  354. ape->frames[ape->currentframe].size);
  355. ape->currentframe++;
  356. return AVERROR(EIO);
  357. }
  358. if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0)
  359. return AVERROR(ENOMEM);
  360. AV_WL32(pkt->data , nblocks);
  361. AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
  362. ret = avio_read(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
  363. if (ret < 0) {
  364. av_free_packet(pkt);
  365. return ret;
  366. }
  367. pkt->pts = ape->frames[ape->currentframe].pts;
  368. pkt->stream_index = 0;
  369. /* note: we need to modify the packet size here to handle the last
  370. packet */
  371. pkt->size = ret + extra_size;
  372. ape->currentframe++;
  373. return 0;
  374. }
  375. static int ape_read_close(AVFormatContext * s)
  376. {
  377. APEContext *ape = s->priv_data;
  378. av_freep(&ape->frames);
  379. av_freep(&ape->seektable);
  380. av_freep(&ape->bittable);
  381. return 0;
  382. }
  383. static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  384. {
  385. AVStream *st = s->streams[stream_index];
  386. APEContext *ape = s->priv_data;
  387. int index = av_index_search_timestamp(st, timestamp, flags);
  388. if (index < 0)
  389. return -1;
  390. if (avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET) < 0)
  391. return -1;
  392. ape->currentframe = index;
  393. return 0;
  394. }
  395. AVInputFormat ff_ape_demuxer = {
  396. .name = "ape",
  397. .long_name = NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  398. .priv_data_size = sizeof(APEContext),
  399. .read_probe = ape_probe,
  400. .read_header = ape_read_header,
  401. .read_packet = ape_read_packet,
  402. .read_close = ape_read_close,
  403. .read_seek = ape_read_seek,
  404. .extensions = "ape,apl,mac",
  405. };