ape.c 16 KB

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