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.

763 lines
29KB

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