flacdec.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. * Raw FLAC demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/channel_layout.h"
  22. #include "libavutil/mem.h"
  23. #include "libavcodec/avcodec.h"
  24. #include "libavcodec/bytestream.h"
  25. #include "libavcodec/flac.h"
  26. #include "avformat.h"
  27. #include "avio_internal.h"
  28. #include "demux.h"
  29. #include "flac_picture.h"
  30. #include "internal.h"
  31. #include "rawdec.h"
  32. #include "oggdec.h"
  33. #include "replaygain.h"
  34. #define SEEKPOINT_SIZE 18
  35. typedef struct FLACDecContext {
  36. FFRawDemuxerContext rawctx;
  37. int found_seektable;
  38. AVCodecContext *parser_dec;
  39. } FLACDecContext;
  40. static void reset_index_position(int64_t metadata_head_size, AVStream *st)
  41. {
  42. FFStream *const sti = ffstream(st);
  43. /* the real seek index offset should be the size of metadata blocks with the offset in the frame blocks */
  44. for (int i = 0; i < sti->nb_index_entries; i++)
  45. sti->index_entries[i].pos += metadata_head_size;
  46. }
  47. static const uint16_t sr_table[16] = {
  48. 0, 1764, 3528, 3840, 160, 320, 441, 480, 640, 882, 960, 1920, 0, 0, 0, 0
  49. };
  50. static int flac_read_header(AVFormatContext *s)
  51. {
  52. int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;
  53. uint8_t header[4];
  54. uint8_t *buffer=NULL;
  55. uint32_t marker;
  56. FLACDecContext *flac = s->priv_data;
  57. AVStream *st = avformat_new_stream(s, NULL);
  58. if (!st)
  59. return AVERROR(ENOMEM);
  60. st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;
  61. st->codecpar->codec_id = AV_CODEC_ID_FLAC;
  62. ffstream(st)->need_parsing = AVSTREAM_PARSE_FULL_RAW;
  63. /* the parameters will be extracted from the compressed bitstream */
  64. /* if fLaC marker is not found, assume there is no header */
  65. marker = avio_rl32(s->pb);
  66. if (marker != MKTAG('f','L','a','C')) {
  67. const int sample_rate = 50 * sr_table[(marker >> 16) & 0xF];
  68. if (sample_rate)
  69. avpriv_set_pts_info(st, 64, 1, sample_rate);
  70. avio_seek(s->pb, -4, SEEK_CUR);
  71. return 0;
  72. }
  73. /* process metadata blocks */
  74. while (!avio_feof(s->pb) && !metadata_last) {
  75. ret = avio_read(s->pb, header, 4);
  76. if (ret < 0) {
  77. return ret;
  78. } else if (ret != 4) {
  79. return AVERROR_EOF;
  80. }
  81. flac_parse_block_header(header, &metadata_last, &metadata_type,
  82. &metadata_size);
  83. switch (metadata_type) {
  84. /* allocate and read metadata block for supported types */
  85. case FLAC_METADATA_TYPE_STREAMINFO:
  86. case FLAC_METADATA_TYPE_CUESHEET:
  87. case FLAC_METADATA_TYPE_PICTURE:
  88. case FLAC_METADATA_TYPE_VORBIS_COMMENT:
  89. case FLAC_METADATA_TYPE_SEEKTABLE:
  90. buffer = av_mallocz(metadata_size + AV_INPUT_BUFFER_PADDING_SIZE);
  91. if (!buffer) {
  92. return AVERROR(ENOMEM);
  93. }
  94. ret = ffio_read_size(s->pb, buffer, metadata_size);
  95. if (ret < 0) {
  96. RETURN_ERROR(ret);
  97. }
  98. break;
  99. /* skip metadata block for unsupported types */
  100. default:
  101. ret = avio_skip(s->pb, metadata_size);
  102. if (ret < 0)
  103. return ret;
  104. }
  105. if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {
  106. uint32_t samplerate;
  107. uint64_t samples;
  108. /* STREAMINFO can only occur once */
  109. if (found_streaminfo) {
  110. RETURN_ERROR(AVERROR_INVALIDDATA);
  111. }
  112. if (metadata_size != FLAC_STREAMINFO_SIZE) {
  113. RETURN_ERROR(AVERROR_INVALIDDATA);
  114. }
  115. found_streaminfo = 1;
  116. st->codecpar->extradata = buffer;
  117. st->codecpar->extradata_size = metadata_size;
  118. buffer = NULL;
  119. /* get sample rate and sample count from STREAMINFO header;
  120. * other parameters will be extracted by the parser */
  121. samplerate = AV_RB24(st->codecpar->extradata + 10) >> 4;
  122. samples = (AV_RB64(st->codecpar->extradata + 13) >> 24) & ((1ULL << 36) - 1);
  123. /* set time base and duration */
  124. if (samplerate > 0) {
  125. avpriv_set_pts_info(st, 64, 1, samplerate);
  126. if (samples > 0)
  127. st->duration = samples;
  128. }
  129. } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {
  130. uint8_t isrc[13];
  131. uint64_t start;
  132. const uint8_t *offset;
  133. int i, chapters, track, ti;
  134. if (metadata_size < 431)
  135. RETURN_ERROR(AVERROR_INVALIDDATA);
  136. offset = buffer + 395;
  137. chapters = bytestream_get_byte(&offset) - 1;
  138. if (chapters <= 0)
  139. RETURN_ERROR(AVERROR_INVALIDDATA);
  140. for (i = 0; i < chapters; i++) {
  141. if (offset + 36 - buffer > metadata_size)
  142. RETURN_ERROR(AVERROR_INVALIDDATA);
  143. start = bytestream_get_be64(&offset);
  144. track = bytestream_get_byte(&offset);
  145. bytestream_get_buffer(&offset, isrc, 12);
  146. isrc[12] = 0;
  147. offset += 14;
  148. ti = bytestream_get_byte(&offset);
  149. if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);
  150. offset += ti * 12;
  151. avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);
  152. }
  153. av_freep(&buffer);
  154. } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {
  155. ret = ff_flac_parse_picture(s, &buffer, metadata_size, 1);
  156. av_freep(&buffer);
  157. if (ret < 0) {
  158. av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");
  159. return ret;
  160. }
  161. } else if (metadata_type == FLAC_METADATA_TYPE_SEEKTABLE) {
  162. const uint8_t *seekpoint = buffer;
  163. int i, seek_point_count = metadata_size/SEEKPOINT_SIZE;
  164. flac->found_seektable = 1;
  165. if ((s->flags&AVFMT_FLAG_FAST_SEEK)) {
  166. for(i=0; i<seek_point_count; i++) {
  167. int64_t timestamp = bytestream_get_be64(&seekpoint);
  168. int64_t pos = bytestream_get_be64(&seekpoint);
  169. /* skip number of samples */
  170. bytestream_get_be16(&seekpoint);
  171. av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);
  172. }
  173. }
  174. av_freep(&buffer);
  175. }
  176. else {
  177. /* STREAMINFO must be the first block */
  178. if (!found_streaminfo) {
  179. RETURN_ERROR(AVERROR_INVALIDDATA);
  180. }
  181. /* process supported blocks other than STREAMINFO */
  182. if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {
  183. AVDictionaryEntry *chmask;
  184. ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);
  185. if (ret < 0) {
  186. av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");
  187. } else if (ret > 0) {
  188. s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  189. }
  190. /* parse the channels mask if present */
  191. chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
  192. if (chmask) {
  193. uint64_t mask = strtol(chmask->value, NULL, 0);
  194. if (!mask || mask & ~0x3ffffULL) {
  195. av_log(s, AV_LOG_WARNING,
  196. "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");
  197. } else {
  198. av_channel_layout_from_mask(&st->codecpar->ch_layout, mask);
  199. av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);
  200. }
  201. }
  202. }
  203. av_freep(&buffer);
  204. }
  205. }
  206. ret = ff_replaygain_export(st, s->metadata);
  207. if (ret < 0)
  208. return ret;
  209. reset_index_position(avio_tell(s->pb), st);
  210. return 0;
  211. fail:
  212. av_free(buffer);
  213. return ret;
  214. }
  215. static int raw_flac_probe(const AVProbeData *p)
  216. {
  217. if ((p->buf[2] & 0xF0) == 0) // blocksize code invalid
  218. return 0;
  219. if ((p->buf[2] & 0x0F) == 0x0F) // sample rate code invalid
  220. return 0;
  221. if ((p->buf[3] & 0xF0) >= FLAC_MAX_CHANNELS + FLAC_CHMODE_MID_SIDE << 4)
  222. // channel mode invalid
  223. return 0;
  224. if ((p->buf[3] & 0x06) == 0x06) // bits per sample code invalid
  225. return 0;
  226. if ((p->buf[3] & 0x01) == 0x01) // reserved bit set
  227. return 0;
  228. return AVPROBE_SCORE_EXTENSION / 4 + 1;
  229. }
  230. static int flac_probe(const AVProbeData *p)
  231. {
  232. if ((AV_RB16(p->buf) & 0xFFFE) == 0xFFF8)
  233. return raw_flac_probe(p);
  234. /* file header + metadata header + checked bytes of streaminfo */
  235. if (p->buf_size >= 4 + 4 + 13) {
  236. int type = p->buf[4] & 0x7f;
  237. int size = AV_RB24(p->buf + 5);
  238. int min_block_size = AV_RB16(p->buf + 8);
  239. int max_block_size = AV_RB16(p->buf + 10);
  240. int sample_rate = AV_RB24(p->buf + 18) >> 4;
  241. if (memcmp(p->buf, "fLaC", 4))
  242. return 0;
  243. if (type == FLAC_METADATA_TYPE_STREAMINFO &&
  244. size == FLAC_STREAMINFO_SIZE &&
  245. min_block_size >= 16 &&
  246. max_block_size >= min_block_size &&
  247. sample_rate && sample_rate <= 655350)
  248. return AVPROBE_SCORE_MAX;
  249. return AVPROBE_SCORE_EXTENSION;
  250. }
  251. return 0;
  252. }
  253. av_unused static int64_t flac_read_timestamp(AVFormatContext *s, int stream_index,
  254. int64_t *ppos, int64_t pos_limit)
  255. {
  256. FLACDecContext *flac = s->priv_data;
  257. FFFormatContext *const si = ffformatcontext(s);
  258. AVPacket *const pkt = si->parse_pkt;
  259. AVStream *st = s->streams[stream_index];
  260. AVCodecParserContext *parser;
  261. int ret;
  262. int64_t pts = AV_NOPTS_VALUE;
  263. if (avio_seek(s->pb, *ppos, SEEK_SET) < 0)
  264. return AV_NOPTS_VALUE;
  265. if (!flac->parser_dec) {
  266. flac->parser_dec = avcodec_alloc_context3(NULL);
  267. if (!flac->parser_dec)
  268. return AV_NOPTS_VALUE;
  269. ret = avcodec_parameters_to_context(flac->parser_dec, st->codecpar);
  270. if (ret < 0)
  271. return ret;
  272. }
  273. parser = av_parser_init(st->codecpar->codec_id);
  274. if (!parser)
  275. return AV_NOPTS_VALUE;
  276. parser->flags |= PARSER_FLAG_USE_CODEC_TS;
  277. for (;;){
  278. uint8_t *data;
  279. int size;
  280. ret = ff_raw_read_partial_packet(s, pkt);
  281. if (ret < 0){
  282. if (ret == AVERROR(EAGAIN))
  283. continue;
  284. else {
  285. av_packet_unref(pkt);
  286. av_assert1(!pkt->size);
  287. }
  288. }
  289. av_parser_parse2(parser, flac->parser_dec,
  290. &data, &size, pkt->data, pkt->size,
  291. pkt->pts, pkt->dts, *ppos);
  292. av_packet_unref(pkt);
  293. if (size) {
  294. if (parser->pts != AV_NOPTS_VALUE){
  295. // seeking may not have started from beginning of a frame
  296. // calculate frame start position from next frame backwards
  297. *ppos = parser->next_frame_offset - size;
  298. pts = parser->pts;
  299. break;
  300. }
  301. } else if (ret < 0)
  302. break;
  303. }
  304. av_parser_close(parser);
  305. return pts;
  306. }
  307. static int flac_close(AVFormatContext *s)
  308. {
  309. FLACDecContext *flac = s->priv_data;
  310. avcodec_free_context(&flac->parser_dec);
  311. return 0;
  312. }
  313. static int flac_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) {
  314. AVStream *const st = s->streams[0];
  315. FFStream *const sti = ffstream(st);
  316. int index;
  317. int64_t pos;
  318. AVIndexEntry e;
  319. FLACDecContext *flac = s->priv_data;
  320. if (!flac->found_seektable || !(s->flags&AVFMT_FLAG_FAST_SEEK)) {
  321. return -1;
  322. }
  323. index = av_index_search_timestamp(st, timestamp, flags);
  324. if (index < 0 || index >= sti->nb_index_entries)
  325. return -1;
  326. e = sti->index_entries[index];
  327. pos = avio_seek(s->pb, e.pos, SEEK_SET);
  328. if (pos >= 0) {
  329. return 0;
  330. }
  331. return -1;
  332. }
  333. const FFInputFormat ff_flac_demuxer = {
  334. .p.name = "flac",
  335. .p.long_name = NULL_IF_CONFIG_SMALL("raw FLAC"),
  336. .p.flags = AVFMT_GENERIC_INDEX,
  337. .p.extensions = "flac",
  338. .p.priv_class = &ff_raw_demuxer_class,
  339. .read_probe = flac_probe,
  340. .read_header = flac_read_header,
  341. .read_close = flac_close,
  342. .read_packet = ff_raw_read_partial_packet,
  343. .read_seek = flac_seek,
  344. .read_timestamp = flac_read_timestamp,
  345. .raw_codec_id = AV_CODEC_ID_FLAC,
  346. .priv_data_size = sizeof(FLACDecContext),
  347. .flags_internal = FF_INFMT_FLAG_ID3V2_AUTO,
  348. };