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.

684 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. 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. fpc->avctx->sample_rate = header->fi.samplerate;
  407. fpc->avctx->channels = header->fi.channels;
  408. fpc->pc->duration = header->fi.blocksize;
  409. *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
  410. &fpc->wrap_buf,
  411. &fpc->wrap_buf_allocated_size);
  412. fpc->best_header_valid = 0;
  413. /* Return the negative overread index so the client can compute pos.
  414. This should be the amount overread to the beginning of the child */
  415. if (child)
  416. return child->offset - av_fifo_size(fpc->fifo_buf);
  417. return 0;
  418. }
  419. static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,
  420. const uint8_t **poutbuf, int *poutbuf_size,
  421. const uint8_t *buf, int buf_size)
  422. {
  423. FLACParseContext *fpc = s->priv_data;
  424. FLACHeaderMarker *curr;
  425. int nb_headers;
  426. const uint8_t *read_end = buf;
  427. const uint8_t *read_start = buf;
  428. if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
  429. FLACFrameInfo fi;
  430. if (frame_header_is_valid(avctx, buf, &fi))
  431. s->duration = fi.blocksize;
  432. *poutbuf = buf;
  433. *poutbuf_size = buf_size;
  434. return buf_size;
  435. }
  436. fpc->avctx = avctx;
  437. if (fpc->best_header_valid)
  438. return get_best_header(fpc, poutbuf, poutbuf_size);
  439. /* If a best_header was found last call remove it with the buffer data. */
  440. if (fpc->best_header && fpc->best_header->best_child) {
  441. FLACHeaderMarker *temp;
  442. FLACHeaderMarker *best_child = fpc->best_header->best_child;
  443. /* Remove headers in list until the end of the best_header. */
  444. for (curr = fpc->headers; curr != best_child; curr = temp) {
  445. if (curr != fpc->best_header) {
  446. av_log(avctx, AV_LOG_DEBUG,
  447. "dropping low score %i frame header from offset %i to %i\n",
  448. curr->max_score, curr->offset, curr->next->offset);
  449. }
  450. temp = curr->next;
  451. av_freep(&curr->link_penalty);
  452. av_free(curr);
  453. fpc->nb_headers_buffered--;
  454. }
  455. /* Release returned data from ring buffer. */
  456. av_fifo_drain(fpc->fifo_buf, best_child->offset);
  457. /* Fix the offset for the headers remaining to match the new buffer. */
  458. for (curr = best_child->next; curr; curr = curr->next)
  459. curr->offset -= best_child->offset;
  460. fpc->nb_headers_buffered--;
  461. best_child->offset = 0;
  462. fpc->headers = best_child;
  463. if (fpc->nb_headers_buffered >= FLAC_MIN_HEADERS) {
  464. fpc->best_header = best_child;
  465. return get_best_header(fpc, poutbuf, poutbuf_size);
  466. }
  467. fpc->best_header = NULL;
  468. } else if (fpc->best_header) {
  469. /* No end frame no need to delete the buffer; probably eof */
  470. FLACHeaderMarker *temp;
  471. for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {
  472. temp = curr->next;
  473. av_freep(&curr->link_penalty);
  474. av_free(curr);
  475. }
  476. fpc->headers = fpc->best_header->next;
  477. av_freep(&fpc->best_header->link_penalty);
  478. av_freep(&fpc->best_header);
  479. }
  480. /* Find and score new headers. */
  481. while ((buf && read_end < buf + buf_size &&
  482. fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
  483. || (!buf && !fpc->end_padded)) {
  484. int start_offset;
  485. /* Pad the end once if EOF, to check the final region for headers. */
  486. if (!buf) {
  487. fpc->end_padded = 1;
  488. buf_size = MAX_FRAME_HEADER_SIZE;
  489. read_end = read_start + MAX_FRAME_HEADER_SIZE;
  490. } else {
  491. /* The maximum read size is the upper-bound of what the parser
  492. needs to have the required number of frames buffered */
  493. int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;
  494. read_end = read_end + FFMIN(buf + buf_size - read_end,
  495. nb_desired * FLAC_AVG_FRAME_SIZE);
  496. }
  497. /* Fill the buffer. */
  498. if ( av_fifo_space(fpc->fifo_buf) < read_end - read_start
  499. && av_fifo_realloc2(fpc->fifo_buf, (read_end - read_start) + 2*av_fifo_size(fpc->fifo_buf)) < 0) {
  500. av_log(avctx, AV_LOG_ERROR,
  501. "couldn't reallocate buffer of size %td\n",
  502. (read_end - read_start) + av_fifo_size(fpc->fifo_buf));
  503. goto handle_error;
  504. }
  505. if (buf) {
  506. av_fifo_generic_write(fpc->fifo_buf, (void*) read_start,
  507. read_end - read_start, NULL);
  508. } else {
  509. int8_t pad[MAX_FRAME_HEADER_SIZE] = { 0 };
  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 duration to 0. It is unknown or invalid in a junk frame. */
  559. s->duration = 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. fpc->pc = c;
  579. /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
  580. it drains. This is allocated early to avoid slow reallocation. */
  581. fpc->fifo_buf = av_fifo_alloc(FLAC_AVG_FRAME_SIZE * (FLAC_MIN_HEADERS + 3));
  582. return 0;
  583. }
  584. static void flac_parse_close(AVCodecParserContext *c)
  585. {
  586. FLACParseContext *fpc = c->priv_data;
  587. FLACHeaderMarker *curr = fpc->headers, *temp;
  588. while (curr) {
  589. temp = curr->next;
  590. av_freep(&curr->link_penalty);
  591. av_free(curr);
  592. curr = temp;
  593. }
  594. av_fifo_free(fpc->fifo_buf);
  595. av_free(fpc->wrap_buf);
  596. }
  597. AVCodecParser ff_flac_parser = {
  598. .codec_ids = { AV_CODEC_ID_FLAC },
  599. .priv_data_size = sizeof(FLACParseContext),
  600. .parser_init = flac_parse_init,
  601. .parser_parse = flac_parse,
  602. .parser_close = flac_parse_close,
  603. };