ape.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 "apetag.h"
  26. /* The earliest and latest file formats supported by this library */
  27. #define APE_MIN_VERSION 3950
  28. #define APE_MAX_VERSION 3990
  29. #define MAC_FORMAT_FLAG_8_BIT 1 // is 8-bit [OBSOLETE]
  30. #define MAC_FORMAT_FLAG_CRC 2 // uses the new CRC32 error detection [OBSOLETE]
  31. #define MAC_FORMAT_FLAG_HAS_PEAK_LEVEL 4 // uint32 nPeakLevel after the header [OBSOLETE]
  32. #define MAC_FORMAT_FLAG_24_BIT 8 // is 24-bit [OBSOLETE]
  33. #define MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS 16 // has the number of seek elements after the peak level
  34. #define MAC_FORMAT_FLAG_CREATE_WAV_HEADER 32 // create the wave header on decompression (not stored)
  35. #define MAC_SUBFRAME_SIZE 4608
  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 %d (%d bytes)\n", i, ape_ctx->seektable[i], ape_ctx->seektable[i + 1] - ape_ctx->seektable[i]);
  115. } else {
  116. av_log(s, AV_LOG_DEBUG, "%8d %d\n", i, ape_ctx->seektable[i]);
  117. }
  118. }
  119. }
  120. av_log(s, AV_LOG_DEBUG, "\nFrames\n\n");
  121. for (i = 0; i < ape_ctx->totalframes; i++)
  122. av_log(s, AV_LOG_DEBUG, "%8d %8"PRId64" %8d (%d samples)\n", i,
  123. ape_ctx->frames[i].pos, ape_ctx->frames[i].size,
  124. ape_ctx->frames[i].nblocks);
  125. av_log(s, AV_LOG_DEBUG, "\nCalculated information:\n\n");
  126. av_log(s, AV_LOG_DEBUG, "junklength = %"PRIu32"\n", ape_ctx->junklength);
  127. av_log(s, AV_LOG_DEBUG, "firstframe = %"PRIu32"\n", ape_ctx->firstframe);
  128. av_log(s, AV_LOG_DEBUG, "totalsamples = %"PRIu32"\n", ape_ctx->totalsamples);
  129. #endif
  130. }
  131. static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap)
  132. {
  133. AVIOContext *pb = s->pb;
  134. APEContext *ape = s->priv_data;
  135. AVStream *st;
  136. uint32_t tag;
  137. int i;
  138. int total_blocks;
  139. int64_t pts;
  140. /* Skip any leading junk such as id3v2 tags */
  141. ape->junklength = avio_tell(pb);
  142. tag = avio_rl32(pb);
  143. if (tag != MKTAG('M', 'A', 'C', ' '))
  144. return -1;
  145. ape->fileversion = avio_rl16(pb);
  146. if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) {
  147. av_log(s, AV_LOG_ERROR, "Unsupported file version - %"PRId16".%02"PRId16"\n",
  148. ape->fileversion / 1000, (ape->fileversion % 1000) / 10);
  149. return -1;
  150. }
  151. if (ape->fileversion >= 3980) {
  152. ape->padding1 = avio_rl16(pb);
  153. ape->descriptorlength = avio_rl32(pb);
  154. ape->headerlength = avio_rl32(pb);
  155. ape->seektablelength = avio_rl32(pb);
  156. ape->wavheaderlength = avio_rl32(pb);
  157. ape->audiodatalength = avio_rl32(pb);
  158. ape->audiodatalength_high = avio_rl32(pb);
  159. ape->wavtaillength = avio_rl32(pb);
  160. avio_read(pb, ape->md5, 16);
  161. /* Skip any unknown bytes at the end of the descriptor.
  162. This is for future compatibility */
  163. if (ape->descriptorlength > 52)
  164. avio_skip(pb, ape->descriptorlength - 52);
  165. /* Read header data */
  166. ape->compressiontype = avio_rl16(pb);
  167. ape->formatflags = avio_rl16(pb);
  168. ape->blocksperframe = avio_rl32(pb);
  169. ape->finalframeblocks = avio_rl32(pb);
  170. ape->totalframes = avio_rl32(pb);
  171. ape->bps = avio_rl16(pb);
  172. ape->channels = avio_rl16(pb);
  173. ape->samplerate = avio_rl32(pb);
  174. } else {
  175. ape->descriptorlength = 0;
  176. ape->headerlength = 32;
  177. ape->compressiontype = avio_rl16(pb);
  178. ape->formatflags = avio_rl16(pb);
  179. ape->channels = avio_rl16(pb);
  180. ape->samplerate = avio_rl32(pb);
  181. ape->wavheaderlength = avio_rl32(pb);
  182. ape->wavtaillength = avio_rl32(pb);
  183. ape->totalframes = avio_rl32(pb);
  184. ape->finalframeblocks = avio_rl32(pb);
  185. if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) {
  186. avio_skip(pb, 4); /* Skip the peak level */
  187. ape->headerlength += 4;
  188. }
  189. if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) {
  190. ape->seektablelength = avio_rl32(pb);
  191. ape->headerlength += 4;
  192. ape->seektablelength *= sizeof(int32_t);
  193. } else
  194. ape->seektablelength = ape->totalframes * sizeof(int32_t);
  195. if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT)
  196. ape->bps = 8;
  197. else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT)
  198. ape->bps = 24;
  199. else
  200. ape->bps = 16;
  201. if (ape->fileversion >= 3950)
  202. ape->blocksperframe = 73728 * 4;
  203. else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000))
  204. ape->blocksperframe = 73728;
  205. else
  206. ape->blocksperframe = 9216;
  207. /* Skip any stored wav header */
  208. if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER))
  209. avio_skip(pb, ape->wavheaderlength);
  210. }
  211. if(!ape->totalframes){
  212. av_log(s, AV_LOG_ERROR, "No frames in the file!\n");
  213. return AVERROR(EINVAL);
  214. }
  215. if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){
  216. av_log(s, AV_LOG_ERROR, "Too many frames: %"PRIu32"\n",
  217. ape->totalframes);
  218. return -1;
  219. }
  220. if (ape->seektablelength && (ape->seektablelength / sizeof(*ape->seektable)) < ape->totalframes) {
  221. av_log(s, AV_LOG_ERROR, "Number of seek entries is less than number of frames: %ld vs. %"PRIu32"\n",
  222. ape->seektablelength / sizeof(*ape->seektable), ape->totalframes);
  223. return AVERROR_INVALIDDATA;
  224. }
  225. ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame));
  226. if(!ape->frames)
  227. return AVERROR(ENOMEM);
  228. ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength;
  229. ape->currentframe = 0;
  230. ape->totalsamples = ape->finalframeblocks;
  231. if (ape->totalframes > 1)
  232. ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1);
  233. if (ape->seektablelength > 0) {
  234. ape->seektable = av_malloc(ape->seektablelength);
  235. if (!ape->seektable)
  236. return AVERROR(ENOMEM);
  237. for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++)
  238. ape->seektable[i] = avio_rl32(pb);
  239. }else{
  240. av_log(s, AV_LOG_ERROR, "Missing seektable\n");
  241. return -1;
  242. }
  243. ape->frames[0].pos = ape->firstframe;
  244. ape->frames[0].nblocks = ape->blocksperframe;
  245. ape->frames[0].skip = 0;
  246. for (i = 1; i < ape->totalframes; i++) {
  247. ape->frames[i].pos = ape->seektable[i] + ape->junklength;
  248. ape->frames[i].nblocks = ape->blocksperframe;
  249. ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos;
  250. ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3;
  251. }
  252. ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4;
  253. ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks;
  254. for (i = 0; i < ape->totalframes; i++) {
  255. if(ape->frames[i].skip){
  256. ape->frames[i].pos -= ape->frames[i].skip;
  257. ape->frames[i].size += ape->frames[i].skip;
  258. }
  259. ape->frames[i].size = (ape->frames[i].size + 3) & ~3;
  260. }
  261. ape_dumpinfo(s, ape);
  262. /* try to read APE tags */
  263. if (pb->seekable) {
  264. ff_ape_parse_tag(s);
  265. avio_seek(pb, 0, SEEK_SET);
  266. }
  267. av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %"PRIu16"\n",
  268. ape->fileversion / 1000, (ape->fileversion % 1000) / 10,
  269. ape->compressiontype);
  270. /* now we are ready: build format streams */
  271. st = av_new_stream(s, 0);
  272. if (!st)
  273. return -1;
  274. total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks;
  275. st->codec->codec_type = AVMEDIA_TYPE_AUDIO;
  276. st->codec->codec_id = CODEC_ID_APE;
  277. st->codec->codec_tag = MKTAG('A', 'P', 'E', ' ');
  278. st->codec->channels = ape->channels;
  279. st->codec->sample_rate = ape->samplerate;
  280. st->codec->bits_per_coded_sample = ape->bps;
  281. st->codec->frame_size = MAC_SUBFRAME_SIZE;
  282. st->nb_frames = ape->totalframes;
  283. st->start_time = 0;
  284. st->duration = total_blocks / MAC_SUBFRAME_SIZE;
  285. av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate);
  286. st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE);
  287. st->codec->extradata_size = APE_EXTRADATA_SIZE;
  288. AV_WL16(st->codec->extradata + 0, ape->fileversion);
  289. AV_WL16(st->codec->extradata + 2, ape->compressiontype);
  290. AV_WL16(st->codec->extradata + 4, ape->formatflags);
  291. pts = 0;
  292. for (i = 0; i < ape->totalframes; i++) {
  293. ape->frames[i].pts = pts;
  294. av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME);
  295. pts += ape->blocksperframe / MAC_SUBFRAME_SIZE;
  296. }
  297. return 0;
  298. }
  299. static int ape_read_packet(AVFormatContext * s, AVPacket * pkt)
  300. {
  301. int ret;
  302. int nblocks;
  303. APEContext *ape = s->priv_data;
  304. uint32_t extra_size = 8;
  305. if (url_feof(s->pb))
  306. return AVERROR(EIO);
  307. if (ape->currentframe > ape->totalframes)
  308. return AVERROR(EIO);
  309. avio_seek (s->pb, ape->frames[ape->currentframe].pos, SEEK_SET);
  310. /* Calculate how many blocks there are in this frame */
  311. if (ape->currentframe == (ape->totalframes - 1))
  312. nblocks = ape->finalframeblocks;
  313. else
  314. nblocks = ape->blocksperframe;
  315. if (av_new_packet(pkt, ape->frames[ape->currentframe].size + extra_size) < 0)
  316. return AVERROR(ENOMEM);
  317. AV_WL32(pkt->data , nblocks);
  318. AV_WL32(pkt->data + 4, ape->frames[ape->currentframe].skip);
  319. ret = avio_read(s->pb, pkt->data + extra_size, ape->frames[ape->currentframe].size);
  320. pkt->pts = ape->frames[ape->currentframe].pts;
  321. pkt->stream_index = 0;
  322. /* note: we need to modify the packet size here to handle the last
  323. packet */
  324. pkt->size = ret + extra_size;
  325. ape->currentframe++;
  326. return 0;
  327. }
  328. static int ape_read_close(AVFormatContext * s)
  329. {
  330. APEContext *ape = s->priv_data;
  331. av_freep(&ape->frames);
  332. av_freep(&ape->seektable);
  333. return 0;
  334. }
  335. static int ape_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  336. {
  337. AVStream *st = s->streams[stream_index];
  338. APEContext *ape = s->priv_data;
  339. int index = av_index_search_timestamp(st, timestamp, flags);
  340. if (index < 0)
  341. return -1;
  342. ape->currentframe = index;
  343. return 0;
  344. }
  345. AVInputFormat ff_ape_demuxer = {
  346. "ape",
  347. NULL_IF_CONFIG_SMALL("Monkey's Audio"),
  348. sizeof(APEContext),
  349. ape_probe,
  350. ape_read_header,
  351. ape_read_packet,
  352. ape_read_close,
  353. ape_read_seek,
  354. .extensions = "ape,apl,mac"
  355. };