ape.c 17 KB

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