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.

688 lines
26KB

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