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.

748 lines
29KB

  1. /*
  2. * FLAC parser
  3. * Copyright (c) 2010 Michael Chinen
  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. /**
  22. * @file
  23. * FLAC parser
  24. *
  25. * The FLAC parser buffers input until FLAC_MIN_HEADERS has been found.
  26. * Each time it finds and verifies a CRC-8 header it sees which of the
  27. * FLAC_MAX_SEQUENTIAL_HEADERS that came before it have a valid CRC-16 footer
  28. * that ends at the newly found header.
  29. * Headers are scored by FLAC_HEADER_BASE_SCORE plus the max of its crc-verified
  30. * children, penalized by changes in sample rate, frame number, etc.
  31. * The parser returns the frame with the highest score.
  32. **/
  33. #include "libavutil/attributes.h"
  34. #include "libavutil/crc.h"
  35. #include "libavutil/fifo.h"
  36. #include "bytestream.h"
  37. #include "parser.h"
  38. #include "flac.h"
  39. /** maximum number of adjacent headers that compare CRCs against each other */
  40. #define FLAC_MAX_SEQUENTIAL_HEADERS 4
  41. /** minimum number of headers buffered and checked before returning frames */
  42. #define FLAC_MIN_HEADERS 10
  43. /** estimate for average size of a FLAC frame */
  44. #define FLAC_AVG_FRAME_SIZE 8192
  45. /** scoring settings for score_header */
  46. #define FLAC_HEADER_BASE_SCORE 10
  47. #define FLAC_HEADER_CHANGED_PENALTY 7
  48. #define FLAC_HEADER_CRC_FAIL_PENALTY 50
  49. #define FLAC_HEADER_NOT_PENALIZED_YET 100000
  50. #define FLAC_HEADER_NOT_SCORED_YET -100000
  51. /** largest possible size of flac header */
  52. #define MAX_FRAME_HEADER_SIZE 16
  53. typedef struct FLACHeaderMarker {
  54. int offset; /**< byte offset from start of FLACParseContext->buffer */
  55. int link_penalty[FLAC_MAX_SEQUENTIAL_HEADERS]; /**< array of local scores
  56. between this header and the one at a distance equal
  57. array position */
  58. int max_score; /**< maximum score found after checking each child that
  59. has a valid CRC */
  60. FLACFrameInfo fi; /**< decoded frame header info */
  61. struct FLACHeaderMarker *next; /**< next CRC-8 verified header that
  62. immediately follows this one in
  63. the bytestream */
  64. struct FLACHeaderMarker *best_child; /**< following frame header with
  65. which this frame has the best
  66. score with */
  67. } FLACHeaderMarker;
  68. typedef struct FLACParseContext {
  69. AVCodecParserContext *pc; /**< parent context */
  70. AVCodecContext *avctx; /**< codec context pointer for logging */
  71. FLACHeaderMarker *headers; /**< linked-list that starts at the first
  72. CRC-8 verified header within buffer */
  73. FLACHeaderMarker *best_header; /**< highest scoring header within buffer */
  74. int nb_headers_found; /**< number of headers found in the last
  75. flac_parse() call */
  76. int nb_headers_buffered; /**< number of headers that are buffered */
  77. int best_header_valid; /**< flag set when the parser returns junk;
  78. if set return best_header next time */
  79. AVFifoBuffer *fifo_buf; /**< buffer to store all data until headers
  80. can be verified */
  81. int end_padded; /**< specifies if fifo_buf's end is padded */
  82. uint8_t *wrap_buf; /**< general fifo read buffer when wrapped */
  83. int wrap_buf_allocated_size; /**< actual allocated size of the buffer */
  84. FLACFrameInfo last_fi; /**< last decoded frame header info */
  85. int last_fi_valid; /**< set if last_fi is valid */
  86. } FLACParseContext;
  87. static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf,
  88. FLACFrameInfo *fi)
  89. {
  90. GetBitContext gb;
  91. init_get_bits(&gb, buf, MAX_FRAME_HEADER_SIZE * 8);
  92. return !ff_flac_decode_frame_header(avctx, &gb, fi, 127);
  93. }
  94. /**
  95. * Non-destructive fast fifo pointer fetching
  96. * Returns a pointer from the specified offset.
  97. * If possible the pointer points within the fifo buffer.
  98. * Otherwise (if it would cause a wrap around,) a pointer to a user-specified
  99. * buffer is used.
  100. * The pointer can be NULL. In any case it will be reallocated to hold the size.
  101. * If the returned pointer will be used after subsequent calls to flac_fifo_read_wrap
  102. * then the subsequent calls should pass in a different wrap_buf so as to not
  103. * overwrite the contents of the previous wrap_buf.
  104. * This function is based on av_fifo_generic_read, which is why there is a comment
  105. * about a memory barrier for SMP.
  106. */
  107. static uint8_t *flac_fifo_read_wrap(FLACParseContext *fpc, int offset, int len,
  108. uint8_t **wrap_buf, int *allocated_size)
  109. {
  110. AVFifoBuffer *f = fpc->fifo_buf;
  111. uint8_t *start = f->rptr + offset;
  112. uint8_t *tmp_buf;
  113. if (start >= f->end)
  114. start -= f->end - f->buffer;
  115. if (f->end - start >= len)
  116. return start;
  117. tmp_buf = av_fast_realloc(*wrap_buf, allocated_size, len);
  118. if (!tmp_buf) {
  119. av_log(fpc->avctx, AV_LOG_ERROR,
  120. "couldn't reallocate wrap buffer of size %d", len);
  121. return NULL;
  122. }
  123. *wrap_buf = tmp_buf;
  124. do {
  125. int seg_len = FFMIN(f->end - start, len);
  126. memcpy(tmp_buf, start, seg_len);
  127. tmp_buf = (uint8_t*)tmp_buf + seg_len;
  128. // memory barrier needed for SMP here in theory
  129. start += seg_len - (f->end - f->buffer);
  130. len -= seg_len;
  131. } while (len > 0);
  132. return *wrap_buf;
  133. }
  134. /**
  135. * Return a pointer in the fifo buffer where the offset starts at until
  136. * the wrap point or end of request.
  137. * len will contain the valid length of the returned buffer.
  138. * A second call to flac_fifo_read (with new offset and len) should be called
  139. * to get the post-wrap buf if the returned len is less than the requested.
  140. **/
  141. static uint8_t *flac_fifo_read(FLACParseContext *fpc, int offset, int *len)
  142. {
  143. AVFifoBuffer *f = fpc->fifo_buf;
  144. uint8_t *start = f->rptr + offset;
  145. if (start >= f->end)
  146. start -= f->end - f->buffer;
  147. *len = FFMIN(*len, f->end - start);
  148. return start;
  149. }
  150. static int find_headers_search_validate(FLACParseContext *fpc, int offset)
  151. {
  152. FLACFrameInfo fi;
  153. uint8_t *header_buf;
  154. int size = 0;
  155. header_buf = flac_fifo_read_wrap(fpc, offset,
  156. MAX_FRAME_HEADER_SIZE,
  157. &fpc->wrap_buf,
  158. &fpc->wrap_buf_allocated_size);
  159. if (frame_header_is_valid(fpc->avctx, header_buf, &fi)) {
  160. FLACHeaderMarker **end_handle = &fpc->headers;
  161. int i;
  162. size = 0;
  163. while (*end_handle) {
  164. end_handle = &(*end_handle)->next;
  165. size++;
  166. }
  167. *end_handle = av_mallocz(sizeof(**end_handle));
  168. if (!*end_handle) {
  169. av_log(fpc->avctx, AV_LOG_ERROR,
  170. "couldn't allocate FLACHeaderMarker\n");
  171. return AVERROR(ENOMEM);
  172. }
  173. (*end_handle)->fi = fi;
  174. (*end_handle)->offset = offset;
  175. for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++)
  176. (*end_handle)->link_penalty[i] = FLAC_HEADER_NOT_PENALIZED_YET;
  177. fpc->nb_headers_found++;
  178. size++;
  179. }
  180. return size;
  181. }
  182. static int find_headers_search(FLACParseContext *fpc, uint8_t *buf,
  183. int buf_size, int search_start)
  184. {
  185. int size = 0, mod_offset = (buf_size - 1) % 4, i, j;
  186. uint32_t x;
  187. for (i = 0; i < mod_offset; i++) {
  188. if ((AV_RB16(buf + i) & 0xFFFE) == 0xFFF8)
  189. size = find_headers_search_validate(fpc, search_start + i);
  190. }
  191. for (; i < buf_size - 1; i += 4) {
  192. x = AV_RN32(buf + i);
  193. if (((x & ~(x + 0x01010101)) & 0x80808080)) {
  194. for (j = 0; j < 4; j++) {
  195. if ((AV_RB16(buf + i + j) & 0xFFFE) == 0xFFF8)
  196. size = find_headers_search_validate(fpc, search_start + i + j);
  197. }
  198. }
  199. }
  200. return size;
  201. }
  202. static int find_new_headers(FLACParseContext *fpc, int search_start)
  203. {
  204. FLACHeaderMarker *end;
  205. int search_end, size = 0, read_len, temp;
  206. uint8_t *buf;
  207. fpc->nb_headers_found = 0;
  208. /* Search for a new header of at most 16 bytes. */
  209. search_end = av_fifo_size(fpc->fifo_buf) - (MAX_FRAME_HEADER_SIZE - 1);
  210. read_len = search_end - search_start + 1;
  211. buf = flac_fifo_read(fpc, search_start, &read_len);
  212. size = find_headers_search(fpc, buf, read_len, search_start);
  213. search_start += read_len - 1;
  214. /* If fifo end was hit do the wrap around. */
  215. if (search_start != search_end) {
  216. uint8_t wrap[2];
  217. wrap[0] = buf[read_len - 1];
  218. /* search_start + 1 is the post-wrap offset in the fifo. */
  219. read_len = search_end - (search_start + 1) + 1;
  220. buf = flac_fifo_read(fpc, search_start + 1, &read_len);
  221. wrap[1] = buf[0];
  222. if ((AV_RB16(wrap) & 0xFFFE) == 0xFFF8) {
  223. temp = find_headers_search_validate(fpc, search_start);
  224. size = FFMAX(size, temp);
  225. }
  226. search_start++;
  227. /* Continue to do the last half of the wrap. */
  228. temp = find_headers_search(fpc, buf, read_len, search_start);
  229. size = FFMAX(size, temp);
  230. search_start += read_len - 1;
  231. }
  232. /* Return the size even if no new headers were found. */
  233. if (!size && fpc->headers)
  234. for (end = fpc->headers; end; end = end->next)
  235. size++;
  236. return size;
  237. }
  238. static int check_header_fi_mismatch(FLACParseContext *fpc,
  239. FLACFrameInfo *header_fi,
  240. FLACFrameInfo *child_fi,
  241. int log_level_offset)
  242. {
  243. int deduction = 0;
  244. if (child_fi->samplerate != header_fi->samplerate) {
  245. deduction += FLAC_HEADER_CHANGED_PENALTY;
  246. av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
  247. "sample rate change detected in adjacent frames\n");
  248. }
  249. if (child_fi->bps != header_fi->bps) {
  250. deduction += FLAC_HEADER_CHANGED_PENALTY;
  251. av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
  252. "bits per sample change detected in adjacent frames\n");
  253. }
  254. if (child_fi->is_var_size != header_fi->is_var_size) {
  255. /* Changing blocking strategy not allowed per the spec */
  256. deduction += FLAC_HEADER_BASE_SCORE;
  257. av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
  258. "blocking strategy change detected in adjacent frames\n");
  259. }
  260. if (child_fi->channels != header_fi->channels) {
  261. deduction += FLAC_HEADER_CHANGED_PENALTY;
  262. av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
  263. "number of channels change detected in adjacent frames\n");
  264. }
  265. return deduction;
  266. }
  267. static int check_header_mismatch(FLACParseContext *fpc,
  268. FLACHeaderMarker *header,
  269. FLACHeaderMarker *child,
  270. int log_level_offset)
  271. {
  272. FLACFrameInfo *header_fi = &header->fi, *child_fi = &child->fi;
  273. int deduction, deduction_expected = 0, i;
  274. deduction = check_header_fi_mismatch(fpc, header_fi, child_fi,
  275. log_level_offset);
  276. /* Check sample and frame numbers. */
  277. if ((child_fi->frame_or_sample_num - header_fi->frame_or_sample_num
  278. != header_fi->blocksize) &&
  279. (child_fi->frame_or_sample_num
  280. != header_fi->frame_or_sample_num + 1)) {
  281. FLACHeaderMarker *curr;
  282. int64_t expected_frame_num, expected_sample_num;
  283. /* If there are frames in the middle we expect this deduction,
  284. as they are probably valid and this one follows it */
  285. expected_frame_num = expected_sample_num = header_fi->frame_or_sample_num;
  286. curr = header;
  287. while (curr != child) {
  288. /* Ignore frames that failed all crc checks */
  289. for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++) {
  290. if (curr->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY) {
  291. expected_frame_num++;
  292. expected_sample_num += curr->fi.blocksize;
  293. break;
  294. }
  295. }
  296. curr = curr->next;
  297. }
  298. if (expected_frame_num == child_fi->frame_or_sample_num ||
  299. expected_sample_num == child_fi->frame_or_sample_num)
  300. deduction_expected = deduction ? 0 : 1;
  301. deduction += FLAC_HEADER_CHANGED_PENALTY;
  302. av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
  303. "sample/frame number mismatch in adjacent frames\n");
  304. }
  305. /* If we have suspicious headers, check the CRC between them */
  306. if (deduction && !deduction_expected) {
  307. FLACHeaderMarker *curr;
  308. int read_len;
  309. uint8_t *buf;
  310. uint32_t crc = 1;
  311. int inverted_test = 0;
  312. /* Since CRC is expensive only do it if we haven't yet.
  313. This assumes a CRC penalty is greater than all other check penalties */
  314. curr = header->next;
  315. for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS && curr != child; i++)
  316. curr = curr->next;
  317. if (header->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY ||
  318. header->link_penalty[i] == FLAC_HEADER_NOT_PENALIZED_YET) {
  319. FLACHeaderMarker *start, *end;
  320. /* Although overlapping chains are scored, the crc should never
  321. have to be computed twice for a single byte. */
  322. start = header;
  323. end = child;
  324. if (i > 0 &&
  325. header->link_penalty[i - 1] >= FLAC_HEADER_CRC_FAIL_PENALTY) {
  326. while (start->next != child)
  327. start = start->next;
  328. inverted_test = 1;
  329. } else if (i > 0 &&
  330. header->next->link_penalty[i-1] >=
  331. FLAC_HEADER_CRC_FAIL_PENALTY ) {
  332. end = header->next;
  333. inverted_test = 1;
  334. }
  335. read_len = end->offset - start->offset;
  336. buf = flac_fifo_read(fpc, start->offset, &read_len);
  337. crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf, read_len);
  338. read_len = (end->offset - start->offset) - read_len;
  339. if (read_len) {
  340. buf = flac_fifo_read(fpc, end->offset - read_len, &read_len);
  341. crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), crc, buf, read_len);
  342. }
  343. }
  344. if (!crc ^ !inverted_test) {
  345. deduction += FLAC_HEADER_CRC_FAIL_PENALTY;
  346. av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
  347. "crc check failed from offset %i (frame %"PRId64") to %i (frame %"PRId64")\n",
  348. header->offset, header_fi->frame_or_sample_num,
  349. child->offset, child_fi->frame_or_sample_num);
  350. }
  351. }
  352. return deduction;
  353. }
  354. /**
  355. * Score a header.
  356. *
  357. * Give FLAC_HEADER_BASE_SCORE points to a frame for existing.
  358. * If it has children, (subsequent frames of which the preceding CRC footer
  359. * validates against this one,) then take the maximum score of the children,
  360. * with a penalty of FLAC_HEADER_CHANGED_PENALTY applied for each change to
  361. * bps, sample rate, channels, but not decorrelation mode, or blocksize,
  362. * because it can change often.
  363. **/
  364. static int score_header(FLACParseContext *fpc, FLACHeaderMarker *header)
  365. {
  366. FLACHeaderMarker *child;
  367. int dist = 0;
  368. int child_score;
  369. int base_score = FLAC_HEADER_BASE_SCORE;
  370. if (header->max_score != FLAC_HEADER_NOT_SCORED_YET)
  371. return header->max_score;
  372. /* Modify the base score with changes from the last output header */
  373. if (fpc->last_fi_valid) {
  374. /* Silence the log since this will be repeated if selected */
  375. base_score -= check_header_fi_mismatch(fpc, &fpc->last_fi, &header->fi,
  376. AV_LOG_DEBUG);
  377. }
  378. header->max_score = base_score;
  379. /* Check and compute the children's scores. */
  380. child = header->next;
  381. for (dist = 0; dist < FLAC_MAX_SEQUENTIAL_HEADERS && child; dist++) {
  382. /* Look at the child's frame header info and penalize suspicious
  383. changes between the headers. */
  384. if (header->link_penalty[dist] == FLAC_HEADER_NOT_PENALIZED_YET) {
  385. header->link_penalty[dist] = check_header_mismatch(fpc, header,
  386. child, AV_LOG_DEBUG);
  387. }
  388. child_score = score_header(fpc, child) - header->link_penalty[dist];
  389. if (FLAC_HEADER_BASE_SCORE + child_score > header->max_score) {
  390. /* Keep the child because the frame scoring is dynamic. */
  391. header->best_child = child;
  392. header->max_score = base_score + child_score;
  393. }
  394. child = child->next;
  395. }
  396. return header->max_score;
  397. }
  398. static void score_sequences(FLACParseContext *fpc)
  399. {
  400. FLACHeaderMarker *curr;
  401. int best_score = 0;//FLAC_HEADER_NOT_SCORED_YET;
  402. /* First pass to clear all old scores. */
  403. for (curr = fpc->headers; curr; curr = curr->next)
  404. curr->max_score = FLAC_HEADER_NOT_SCORED_YET;
  405. /* Do a second pass to score them all. */
  406. for (curr = fpc->headers; curr; curr = curr->next) {
  407. if (score_header(fpc, curr) > best_score) {
  408. fpc->best_header = curr;
  409. best_score = curr->max_score;
  410. }
  411. }
  412. }
  413. static int get_best_header(FLACParseContext *fpc, const uint8_t **poutbuf,
  414. int *poutbuf_size)
  415. {
  416. FLACHeaderMarker *header = fpc->best_header;
  417. FLACHeaderMarker *child = header->best_child;
  418. if (!child) {
  419. *poutbuf_size = av_fifo_size(fpc->fifo_buf) - header->offset;
  420. } else {
  421. *poutbuf_size = child->offset - header->offset;
  422. /* If the child has suspicious changes, log them */
  423. check_header_mismatch(fpc, header, child, 0);
  424. }
  425. if (header->fi.channels != fpc->avctx->channels ||
  426. !fpc->avctx->channel_layout) {
  427. fpc->avctx->channels = header->fi.channels;
  428. ff_flac_set_channel_layout(fpc->avctx);
  429. }
  430. fpc->avctx->sample_rate = header->fi.samplerate;
  431. fpc->pc->duration = header->fi.blocksize;
  432. *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
  433. &fpc->wrap_buf,
  434. &fpc->wrap_buf_allocated_size);
  435. if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
  436. if (header->fi.is_var_size)
  437. fpc->pc->pts = header->fi.frame_or_sample_num;
  438. else if (header->best_child)
  439. fpc->pc->pts = header->fi.frame_or_sample_num * header->fi.blocksize;
  440. }
  441. fpc->best_header_valid = 0;
  442. fpc->last_fi_valid = 1;
  443. fpc->last_fi = header->fi;
  444. /* Return the negative overread index so the client can compute pos.
  445. This should be the amount overread to the beginning of the child */
  446. if (child)
  447. return child->offset - av_fifo_size(fpc->fifo_buf);
  448. return 0;
  449. }
  450. static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,
  451. const uint8_t **poutbuf, int *poutbuf_size,
  452. const uint8_t *buf, int buf_size)
  453. {
  454. FLACParseContext *fpc = s->priv_data;
  455. FLACHeaderMarker *curr;
  456. int nb_headers;
  457. const uint8_t *read_end = buf;
  458. const uint8_t *read_start = buf;
  459. if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
  460. FLACFrameInfo fi;
  461. if (frame_header_is_valid(avctx, buf, &fi)) {
  462. s->duration = fi.blocksize;
  463. if (!avctx->sample_rate)
  464. avctx->sample_rate = fi.samplerate;
  465. if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
  466. fpc->pc->pts = fi.frame_or_sample_num;
  467. if (!fi.is_var_size)
  468. fpc->pc->pts *= fi.blocksize;
  469. }
  470. }
  471. *poutbuf = buf;
  472. *poutbuf_size = buf_size;
  473. return buf_size;
  474. }
  475. fpc->avctx = avctx;
  476. if (fpc->best_header_valid)
  477. return get_best_header(fpc, poutbuf, poutbuf_size);
  478. /* If a best_header was found last call remove it with the buffer data. */
  479. if (fpc->best_header && fpc->best_header->best_child) {
  480. FLACHeaderMarker *temp;
  481. FLACHeaderMarker *best_child = fpc->best_header->best_child;
  482. /* Remove headers in list until the end of the best_header. */
  483. for (curr = fpc->headers; curr != best_child; curr = temp) {
  484. if (curr != fpc->best_header) {
  485. av_log(avctx, AV_LOG_DEBUG,
  486. "dropping low score %i frame header from offset %i to %i\n",
  487. curr->max_score, curr->offset, curr->next->offset);
  488. }
  489. temp = curr->next;
  490. av_free(curr);
  491. fpc->nb_headers_buffered--;
  492. }
  493. /* Release returned data from ring buffer. */
  494. av_fifo_drain(fpc->fifo_buf, best_child->offset);
  495. /* Fix the offset for the headers remaining to match the new buffer. */
  496. for (curr = best_child->next; curr; curr = curr->next)
  497. curr->offset -= best_child->offset;
  498. best_child->offset = 0;
  499. fpc->headers = best_child;
  500. if (fpc->nb_headers_buffered >= FLAC_MIN_HEADERS) {
  501. fpc->best_header = best_child;
  502. return get_best_header(fpc, poutbuf, poutbuf_size);
  503. }
  504. fpc->best_header = NULL;
  505. } else if (fpc->best_header) {
  506. /* No end frame no need to delete the buffer; probably eof */
  507. FLACHeaderMarker *temp;
  508. for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {
  509. temp = curr->next;
  510. av_free(curr);
  511. fpc->nb_headers_buffered--;
  512. }
  513. fpc->headers = fpc->best_header->next;
  514. av_freep(&fpc->best_header);
  515. fpc->nb_headers_buffered--;
  516. }
  517. /* Find and score new headers. */
  518. /* buf_size is zero when flushing, so check for this since we do */
  519. /* not want to try to read more input once we have found the end. */
  520. /* Also note that buf can't be NULL. */
  521. while ((buf_size && read_end < buf + buf_size &&
  522. fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
  523. || (!buf_size && !fpc->end_padded)) {
  524. int start_offset;
  525. /* Pad the end once if EOF, to check the final region for headers. */
  526. if (!buf_size) {
  527. fpc->end_padded = 1;
  528. read_end = read_start + MAX_FRAME_HEADER_SIZE;
  529. } else {
  530. /* The maximum read size is the upper-bound of what the parser
  531. needs to have the required number of frames buffered */
  532. int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;
  533. read_end = read_end + FFMIN(buf + buf_size - read_end,
  534. nb_desired * FLAC_AVG_FRAME_SIZE);
  535. }
  536. if (!av_fifo_space(fpc->fifo_buf) &&
  537. av_fifo_size(fpc->fifo_buf) / FLAC_AVG_FRAME_SIZE >
  538. fpc->nb_headers_buffered * 20) {
  539. /* There is less than one valid flac header buffered for 20 headers
  540. * buffered. Therefore the fifo is most likely filled with invalid
  541. * data and the input is not a flac file. */
  542. goto handle_error;
  543. }
  544. /* Fill the buffer. */
  545. if ( av_fifo_space(fpc->fifo_buf) < read_end - read_start
  546. && av_fifo_realloc2(fpc->fifo_buf, (read_end - read_start) + 2*av_fifo_size(fpc->fifo_buf)) < 0) {
  547. av_log(avctx, AV_LOG_ERROR,
  548. "couldn't reallocate buffer of size %"PTRDIFF_SPECIFIER"\n",
  549. (read_end - read_start) + av_fifo_size(fpc->fifo_buf));
  550. goto handle_error;
  551. }
  552. if (buf_size) {
  553. av_fifo_generic_write(fpc->fifo_buf, (void*) read_start,
  554. read_end - read_start, NULL);
  555. } else {
  556. int8_t pad[MAX_FRAME_HEADER_SIZE] = { 0 };
  557. av_fifo_generic_write(fpc->fifo_buf, pad, sizeof(pad), NULL);
  558. }
  559. /* Tag headers and update sequences. */
  560. start_offset = av_fifo_size(fpc->fifo_buf) -
  561. ((read_end - read_start) + (MAX_FRAME_HEADER_SIZE - 1));
  562. start_offset = FFMAX(0, start_offset);
  563. nb_headers = find_new_headers(fpc, start_offset);
  564. if (nb_headers < 0) {
  565. av_log(avctx, AV_LOG_ERROR,
  566. "find_new_headers couldn't allocate FLAC header\n");
  567. goto handle_error;
  568. }
  569. fpc->nb_headers_buffered = nb_headers;
  570. /* Wait till FLAC_MIN_HEADERS to output a valid frame. */
  571. if (!fpc->end_padded && fpc->nb_headers_buffered < FLAC_MIN_HEADERS) {
  572. if (read_end < buf + buf_size) {
  573. read_start = read_end;
  574. continue;
  575. } else {
  576. goto handle_error;
  577. }
  578. }
  579. /* If headers found, update the scores since we have longer chains. */
  580. if (fpc->end_padded || fpc->nb_headers_found)
  581. score_sequences(fpc);
  582. /* restore the state pre-padding */
  583. if (fpc->end_padded) {
  584. int warp = fpc->fifo_buf->wptr - fpc->fifo_buf->buffer < MAX_FRAME_HEADER_SIZE;
  585. /* HACK: drain the tail of the fifo */
  586. fpc->fifo_buf->wptr -= MAX_FRAME_HEADER_SIZE;
  587. fpc->fifo_buf->wndx -= MAX_FRAME_HEADER_SIZE;
  588. if (warp) {
  589. fpc->fifo_buf->wptr += fpc->fifo_buf->end -
  590. fpc->fifo_buf->buffer;
  591. }
  592. read_start = read_end = NULL;
  593. }
  594. }
  595. for (curr = fpc->headers; curr; curr = curr->next) {
  596. if (!fpc->best_header || curr->max_score > fpc->best_header->max_score) {
  597. fpc->best_header = curr;
  598. }
  599. }
  600. if (fpc->best_header && fpc->best_header->max_score <= 0) {
  601. // Only accept a bad header if there is no other option to continue
  602. if (!buf_size || read_end != buf || fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
  603. fpc->best_header = NULL;
  604. }
  605. if (fpc->best_header) {
  606. fpc->best_header_valid = 1;
  607. if (fpc->best_header->offset > 0) {
  608. /* Output a junk frame. */
  609. av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",
  610. fpc->best_header->offset);
  611. /* Set duration to 0. It is unknown or invalid in a junk frame. */
  612. s->duration = 0;
  613. *poutbuf_size = fpc->best_header->offset;
  614. *poutbuf = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,
  615. &fpc->wrap_buf,
  616. &fpc->wrap_buf_allocated_size);
  617. return buf_size ? (read_end - buf) : (fpc->best_header->offset -
  618. av_fifo_size(fpc->fifo_buf));
  619. }
  620. if (!buf_size)
  621. return get_best_header(fpc, poutbuf, poutbuf_size);
  622. }
  623. handle_error:
  624. *poutbuf = NULL;
  625. *poutbuf_size = 0;
  626. return buf_size ? read_end - buf : 0;
  627. }
  628. static av_cold int flac_parse_init(AVCodecParserContext *c)
  629. {
  630. FLACParseContext *fpc = c->priv_data;
  631. fpc->pc = c;
  632. /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
  633. it drains. This is allocated early to avoid slow reallocation. */
  634. fpc->fifo_buf = av_fifo_alloc_array(FLAC_MIN_HEADERS + 3, FLAC_AVG_FRAME_SIZE);
  635. if (!fpc->fifo_buf) {
  636. av_log(fpc->avctx, AV_LOG_ERROR,
  637. "couldn't allocate fifo_buf\n");
  638. return AVERROR(ENOMEM);
  639. }
  640. return 0;
  641. }
  642. static void flac_parse_close(AVCodecParserContext *c)
  643. {
  644. FLACParseContext *fpc = c->priv_data;
  645. FLACHeaderMarker *curr = fpc->headers, *temp;
  646. while (curr) {
  647. temp = curr->next;
  648. av_free(curr);
  649. curr = temp;
  650. }
  651. fpc->headers = NULL;
  652. av_fifo_freep(&fpc->fifo_buf);
  653. av_freep(&fpc->wrap_buf);
  654. }
  655. AVCodecParser ff_flac_parser = {
  656. .codec_ids = { AV_CODEC_ID_FLAC },
  657. .priv_data_size = sizeof(FLACParseContext),
  658. .parser_init = flac_parse_init,
  659. .parser_parse = flac_parse,
  660. .parser_close = flac_parse_close,
  661. };