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.

420 lines
15KB

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