ape.c 16 KB

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