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.

683 lines
26KB

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