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.

464 lines
16KB

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