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.

698 lines
27KB

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