FFmpeg  4.4.9
flac_parser.c
Go to the documentation of this file.
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 /**
23  * @file
24  * FLAC parser
25  *
26  * The FLAC parser buffers input until FLAC_MIN_HEADERS has been found.
27  * Each time it finds and verifies a CRC-8 header it sees which of the
28  * FLAC_MAX_SEQUENTIAL_HEADERS that came before it have a valid CRC-16 footer
29  * that ends at the newly found header.
30  * Headers are scored by FLAC_HEADER_BASE_SCORE plus the max of its crc-verified
31  * children, penalized by changes in sample rate, frame number, etc.
32  * The parser returns the frame with the highest score.
33  **/
34 
35 #include "libavutil/attributes.h"
36 #include "libavutil/crc.h"
37 #include "libavutil/fifo.h"
38 #include "bytestream.h"
39 #include "parser.h"
40 #include "flac.h"
41 
42 /** maximum number of adjacent headers that compare CRCs against each other */
43 #define FLAC_MAX_SEQUENTIAL_HEADERS 4
44 /** minimum number of headers buffered and checked before returning frames */
45 #define FLAC_MIN_HEADERS 10
46 /** estimate for average size of a FLAC frame */
47 #define FLAC_AVG_FRAME_SIZE 8192
48 
49 /** scoring settings for score_header */
50 #define FLAC_HEADER_BASE_SCORE 10
51 #define FLAC_HEADER_CHANGED_PENALTY 7
52 #define FLAC_HEADER_CRC_FAIL_PENALTY 50
53 #define FLAC_HEADER_NOT_PENALIZED_YET 100000
54 #define FLAC_HEADER_NOT_SCORED_YET -100000
55 
56 /** largest possible size of flac header */
57 #define MAX_FRAME_HEADER_SIZE 16
58 #define MAX_FRAME_VERIFY_SIZE (MAX_FRAME_HEADER_SIZE)
59 
60 typedef struct FLACHeaderMarker {
61  int offset; /**< byte offset from start of FLACParseContext->buffer */
62  int link_penalty[FLAC_MAX_SEQUENTIAL_HEADERS]; /**< array of local scores
63  between this header and the one at a distance equal
64  array position */
65  int max_score; /**< maximum score found after checking each child that
66  has a valid CRC */
67  FLACFrameInfo fi; /**< decoded frame header info */
68  struct FLACHeaderMarker *next; /**< next CRC-8 verified header that
69  immediately follows this one in
70  the bytestream */
71  struct FLACHeaderMarker *prev; /**< CRC-8 verified header that
72  immediately precedes this one */
73  struct FLACHeaderMarker *best_child; /**< following frame header with
74  which this frame has the best
75  score with */
77 
78 typedef struct FLACParseContext {
79  AVCodecParserContext *pc; /**< parent context */
80  AVCodecContext *avctx; /**< codec context pointer for logging */
81  FLACHeaderMarker *headers; /**< linked-list that starts at the first
82  CRC-8 verified header within buffer */
83  FLACHeaderMarker *best_header; /**< highest scoring header within buffer */
84  int nb_headers_found; /**< number of headers found in the last
85  flac_parse() call */
86  int nb_headers_buffered; /**< number of headers that are buffered */
87  int best_header_valid; /**< flag set when the parser returns junk;
88  if set return best_header next time */
89  AVFifoBuffer *fifo_buf; /**< buffer to store all data until headers
90  can be verified */
91  int end_padded; /**< specifies if fifo_buf's end is padded */
92  uint8_t *wrap_buf; /**< general fifo read buffer when wrapped */
93  int wrap_buf_allocated_size; /**< actual allocated size of the buffer */
94  FLACFrameInfo last_fi; /**< last decoded frame header info */
95  int last_fi_valid; /**< set if last_fi is valid */
97 
98 static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf,
99  FLACFrameInfo *fi)
100 {
101  GetBitContext gb;
102  init_get_bits(&gb, buf, MAX_FRAME_HEADER_SIZE * 8);
103  return !ff_flac_decode_frame_header(avctx, &gb, fi, 127);
104 }
105 
106 /**
107  * Non-destructive fast fifo pointer fetching
108  * Returns a pointer from the specified offset.
109  * If possible the pointer points within the fifo buffer.
110  * Otherwise (if it would cause a wrap around,) a pointer to a user-specified
111  * buffer is used.
112  * The pointer can be NULL. In any case it will be reallocated to hold the size.
113  * If the returned pointer will be used after subsequent calls to flac_fifo_read_wrap
114  * then the subsequent calls should pass in a different wrap_buf so as to not
115  * overwrite the contents of the previous wrap_buf.
116  * This function is based on av_fifo_generic_read, which is why there is a comment
117  * about a memory barrier for SMP.
118  */
120  uint8_t **wrap_buf, int *allocated_size)
121 {
122  AVFifoBuffer *f = fpc->fifo_buf;
123  uint8_t *start = f->rptr + offset;
124  uint8_t *tmp_buf;
125 
126  if (start >= f->end)
127  start -= f->end - f->buffer;
128  if (f->end - start >= len)
129  return start;
130 
131  tmp_buf = av_fast_realloc(*wrap_buf, allocated_size, len);
132 
133  if (!tmp_buf) {
134  av_log(fpc->avctx, AV_LOG_ERROR,
135  "couldn't reallocate wrap buffer of size %d", len);
136  return NULL;
137  }
138  *wrap_buf = tmp_buf;
139  do {
140  int seg_len = FFMIN(f->end - start, len);
141  memcpy(tmp_buf, start, seg_len);
142  tmp_buf = (uint8_t*)tmp_buf + seg_len;
143 // memory barrier needed for SMP here in theory
144 
145  start += seg_len - (f->end - f->buffer);
146  len -= seg_len;
147  } while (len > 0);
148 
149  return *wrap_buf;
150 }
151 
152 /**
153  * Return a pointer in the fifo buffer where the offset starts at until
154  * the wrap point or end of request.
155  * len will contain the valid length of the returned buffer.
156  * A second call to flac_fifo_read (with new offset and len) should be called
157  * to get the post-wrap buf if the returned len is less than the requested.
158  **/
160 {
161  AVFifoBuffer *f = fpc->fifo_buf;
162  uint8_t *start = f->rptr + offset;
163 
164  if (start >= f->end)
165  start -= f->end - f->buffer;
166  *len = FFMIN(*len, f->end - start);
167  return start;
168 }
169 
171 {
172  FLACFrameInfo fi;
173  uint8_t *header_buf;
174  int size = 0;
175  header_buf = flac_fifo_read_wrap(fpc, offset,
177  &fpc->wrap_buf,
179  if (frame_header_is_valid(fpc->avctx, header_buf, &fi)) {
180  FLACHeaderMarker **end_handle = &fpc->headers, *prev = NULL;
181  int i;
182 
183  size = 0;
184  while (*end_handle) {
185  prev = *end_handle;
186  end_handle = &(*end_handle)->next;
187  size++;
188  }
189 
190  *end_handle = av_mallocz(sizeof(**end_handle));
191  if (!*end_handle) {
192  av_log(fpc->avctx, AV_LOG_ERROR,
193  "couldn't allocate FLACHeaderMarker\n");
194  return AVERROR(ENOMEM);
195  }
196  (*end_handle)->fi = fi;
197  (*end_handle)->offset = offset;
198  (*end_handle)->prev = prev;
199 
200  for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++)
201  (*end_handle)->link_penalty[i] = FLAC_HEADER_NOT_PENALIZED_YET;
202 
203  fpc->nb_headers_found++;
204  size++;
205  }
206  return size;
207 }
208 
210  int buf_size, int search_start)
211 {
212  int size = 0, mod_offset = (buf_size - 1) % 4, i, j;
213  uint32_t x;
214 
215  for (i = 0; i < mod_offset; i++) {
216  if ((AV_RB16(buf + i) & 0xFFFE) == 0xFFF8) {
217  int ret = find_headers_search_validate(fpc, search_start + i);
218  size = FFMAX(size, ret);
219  }
220  }
221 
222  for (; i < buf_size - 1; i += 4) {
223  x = AV_RN32(buf + i);
224  if (((x & ~(x + 0x01010101)) & 0x80808080)) {
225  for (j = 0; j < 4; j++) {
226  if ((AV_RB16(buf + i + j) & 0xFFFE) == 0xFFF8) {
227  int ret = find_headers_search_validate(fpc, search_start + i + j);
228  size = FFMAX(size, ret);
229  }
230  }
231  }
232  }
233  return size;
234 }
235 
236 static int find_new_headers(FLACParseContext *fpc, int search_start)
237 {
238  FLACHeaderMarker *end;
239  int search_end, size = 0, read_len, temp;
240  uint8_t *buf;
241  fpc->nb_headers_found = 0;
242 
243  /* Search for a new header of at most 16 bytes. */
244  search_end = av_fifo_size(fpc->fifo_buf) - (MAX_FRAME_HEADER_SIZE - 1);
245  read_len = search_end - search_start + 1;
246  buf = flac_fifo_read(fpc, search_start, &read_len);
247  size = find_headers_search(fpc, buf, read_len, search_start);
248  search_start += read_len - 1;
249 
250  /* If fifo end was hit do the wrap around. */
251  if (search_start != search_end) {
252  uint8_t wrap[2];
253 
254  wrap[0] = buf[read_len - 1];
255  /* search_start + 1 is the post-wrap offset in the fifo. */
256  read_len = search_end - (search_start + 1) + 1;
257 
258  buf = flac_fifo_read(fpc, search_start + 1, &read_len);
259  wrap[1] = buf[0];
260 
261  if ((AV_RB16(wrap) & 0xFFFE) == 0xFFF8) {
262  temp = find_headers_search_validate(fpc, search_start);
263  size = FFMAX(size, temp);
264  }
265  search_start++;
266 
267  /* Continue to do the last half of the wrap. */
268  temp = find_headers_search(fpc, buf, read_len, search_start);
269  size = FFMAX(size, temp);
270  search_start += read_len - 1;
271  }
272 
273  /* Return the size even if no new headers were found. */
274  if (!size && fpc->headers)
275  for (end = fpc->headers; end; end = end->next)
276  size++;
277  return size;
278 }
279 
281  FLACFrameInfo *header_fi,
282  FLACFrameInfo *child_fi,
283  int log_level_offset)
284 {
285  int deduction = 0;
286  if (child_fi->samplerate != header_fi->samplerate) {
287  deduction += FLAC_HEADER_CHANGED_PENALTY;
288  av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
289  "sample rate change detected in adjacent frames\n");
290  }
291  if (child_fi->bps != header_fi->bps) {
292  deduction += FLAC_HEADER_CHANGED_PENALTY;
293  av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
294  "bits per sample change detected in adjacent frames\n");
295  }
296  if (child_fi->is_var_size != header_fi->is_var_size) {
297  /* Changing blocking strategy not allowed per the spec */
298  deduction += FLAC_HEADER_BASE_SCORE;
299  av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
300  "blocking strategy change detected in adjacent frames\n");
301  }
302  if (child_fi->channels != header_fi->channels) {
303  deduction += FLAC_HEADER_CHANGED_PENALTY;
304  av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
305  "number of channels change detected in adjacent frames\n");
306  }
307  return deduction;
308 }
309 
312  FLACHeaderMarker *child,
313  int log_level_offset)
314 {
315  FLACFrameInfo *header_fi = &header->fi, *child_fi = &child->fi;
316  int deduction, deduction_expected = 0, i;
317  deduction = check_header_fi_mismatch(fpc, header_fi, child_fi,
318  log_level_offset);
319  /* Check sample and frame numbers. */
320  if ((child_fi->frame_or_sample_num - header_fi->frame_or_sample_num
321  != header_fi->blocksize) &&
322  (child_fi->frame_or_sample_num
323  != header_fi->frame_or_sample_num + 1)) {
324  FLACHeaderMarker *curr;
325  int64_t expected_frame_num, expected_sample_num;
326  /* If there are frames in the middle we expect this deduction,
327  as they are probably valid and this one follows it */
328 
329  expected_frame_num = expected_sample_num = header_fi->frame_or_sample_num;
330  curr = header;
331  while (curr != child) {
332  /* Ignore frames that failed all crc checks */
333  for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++) {
335  expected_frame_num++;
336  expected_sample_num += curr->fi.blocksize;
337  break;
338  }
339  }
340  curr = curr->next;
341  }
342 
343  if (expected_frame_num == child_fi->frame_or_sample_num ||
344  expected_sample_num == child_fi->frame_or_sample_num)
345  deduction_expected = deduction ? 0 : 1;
346 
347  deduction += FLAC_HEADER_CHANGED_PENALTY;
348  av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
349  "sample/frame number mismatch in adjacent frames\n");
350  }
351 
352  /* If we have suspicious headers, check the CRC between them */
353  if (deduction && !deduction_expected) {
354  FLACHeaderMarker *curr;
355  int read_len;
356  uint8_t *buf;
357  uint32_t crc = 1;
358  int inverted_test = 0;
359 
360  /* Since CRC is expensive only do it if we haven't yet.
361  This assumes a CRC penalty is greater than all other check penalties */
362  curr = header->next;
363  for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS && curr != child; i++)
364  curr = curr->next;
365 
367 
368  if (header->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY ||
369  header->link_penalty[i] == FLAC_HEADER_NOT_PENALIZED_YET) {
370  FLACHeaderMarker *start, *end;
371 
372  /* Although overlapping chains are scored, the crc should never
373  have to be computed twice for a single byte. */
374  start = header;
375  end = child;
376  if (i > 0 &&
377  header->link_penalty[i - 1] >= FLAC_HEADER_CRC_FAIL_PENALTY) {
378  while (start->next != child)
379  start = start->next;
380  inverted_test = 1;
381  } else if (i > 0 &&
382  header->next->link_penalty[i-1] >=
384  end = header->next;
385  inverted_test = 1;
386  }
387 
388  read_len = end->offset - start->offset;
389  buf = flac_fifo_read(fpc, start->offset, &read_len);
390  crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf, read_len);
391  read_len = (end->offset - start->offset) - read_len;
392 
393  if (read_len) {
394  buf = flac_fifo_read(fpc, end->offset - read_len, &read_len);
395  crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), crc, buf, read_len);
396  }
397  }
398 
399  if (!crc ^ !inverted_test) {
400  deduction += FLAC_HEADER_CRC_FAIL_PENALTY;
401  av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
402  "crc check failed from offset %i (frame %"PRId64") to %i (frame %"PRId64")\n",
403  header->offset, header_fi->frame_or_sample_num,
404  child->offset, child_fi->frame_or_sample_num);
405  }
406  }
407  return deduction;
408 }
409 
410 /**
411  * Score a header.
412  *
413  * Give FLAC_HEADER_BASE_SCORE points to a frame for existing.
414  * If it has children, (subsequent frames of which the preceding CRC footer
415  * validates against this one,) then take the maximum score of the children,
416  * with a penalty of FLAC_HEADER_CHANGED_PENALTY applied for each change to
417  * bps, sample rate, channels, but not decorrelation mode, or blocksize,
418  * because it can change often.
419  **/
421 {
422  FLACHeaderMarker *child;
423  int dist = 0;
424  int child_score;
425  int base_score = FLAC_HEADER_BASE_SCORE;
426  if (header->max_score != FLAC_HEADER_NOT_SCORED_YET)
427  return header->max_score;
428 
429  /* Modify the base score with changes from the last output header */
430  if (fpc->last_fi_valid) {
431  /* Silence the log since this will be repeated if selected */
432  base_score -= check_header_fi_mismatch(fpc, &fpc->last_fi, &header->fi,
433  AV_LOG_DEBUG);
434  }
435 
436  header->max_score = base_score;
437 
438  /* Check and compute the children's scores. */
439  child = header->next;
440  for (dist = 0; dist < FLAC_MAX_SEQUENTIAL_HEADERS && child; dist++) {
441  /* Look at the child's frame header info and penalize suspicious
442  changes between the headers. */
443  if (header->link_penalty[dist] == FLAC_HEADER_NOT_PENALIZED_YET) {
444  header->link_penalty[dist] = check_header_mismatch(fpc, header,
445  child, AV_LOG_DEBUG);
446  }
447  child_score = score_header(fpc, child) - header->link_penalty[dist];
448 
449  if (FLAC_HEADER_BASE_SCORE + child_score > header->max_score) {
450  /* Keep the child because the frame scoring is dynamic. */
451  header->best_child = child;
452  header->max_score = base_score + child_score;
453  }
454  child = child->next;
455  }
456 
457  return header->max_score;
458 }
459 
461 {
462  FLACHeaderMarker *curr, *last = NULL;
463  int best_score = FLAC_HEADER_NOT_SCORED_YET;
464  /* First pass to clear all old scores. */
465  for (curr = fpc->headers; curr; curr = curr->next) {
467  last = curr;
468  }
469 
470  /* Score from the last header backwards, so the children of each header
471  are already scored and score_header() does not recurse. */
472  for (curr = last; curr; curr = curr->prev) {
473  if (score_header(fpc, curr) >= best_score) {
474  fpc->best_header = curr;
475  best_score = curr->max_score;
476  }
477  }
478 }
479 
480 static int get_best_header(FLACParseContext *fpc, const uint8_t **poutbuf,
481  int *poutbuf_size)
482 {
484  FLACHeaderMarker *child = header->best_child;
485  if (!child) {
486  *poutbuf_size = av_fifo_size(fpc->fifo_buf) - header->offset;
487  } else {
488  *poutbuf_size = child->offset - header->offset;
489 
490  /* If the child has suspicious changes, log them */
491  check_header_mismatch(fpc, header, child, 0);
492  }
493 
494  if (header->fi.channels != fpc->avctx->channels ||
495  !fpc->avctx->channel_layout) {
496  fpc->avctx->channels = header->fi.channels;
498  }
499  fpc->avctx->sample_rate = header->fi.samplerate;
500  fpc->pc->duration = header->fi.blocksize;
501  *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
502  &fpc->wrap_buf,
504 
505 
506  if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
507  if (header->fi.is_var_size)
508  fpc->pc->pts = header->fi.frame_or_sample_num;
509  else if (header->best_child)
510  fpc->pc->pts = header->fi.frame_or_sample_num * header->fi.blocksize;
511  }
512 
513  fpc->best_header_valid = 0;
514  fpc->last_fi_valid = 1;
515  fpc->last_fi = header->fi;
516 
517  /* Return the negative overread index so the client can compute pos.
518  This should be the amount overread to the beginning of the child */
519  if (child) {
520  int64_t offset = child->offset - av_fifo_size(fpc->fifo_buf);
521  if (offset > -(1 << 28))
522  return offset;
523  }
524  return 0;
525 }
526 
528  const uint8_t **poutbuf, int *poutbuf_size,
529  const uint8_t *buf, int buf_size)
530 {
531  FLACParseContext *fpc = s->priv_data;
532  FLACHeaderMarker *curr;
533  int nb_headers;
534  const uint8_t *read_end = buf;
535  const uint8_t *read_start = buf;
536 
537  if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
538  FLACFrameInfo fi;
539  if (frame_header_is_valid(avctx, buf, &fi)) {
540  s->duration = fi.blocksize;
541  if (!avctx->sample_rate)
542  avctx->sample_rate = fi.samplerate;
543  if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
544  fpc->pc->pts = fi.frame_or_sample_num;
545  if (!fi.is_var_size)
546  fpc->pc->pts *= fi.blocksize;
547  }
548  }
549  *poutbuf = buf;
550  *poutbuf_size = buf_size;
551  return buf_size;
552  }
553 
554  fpc->avctx = avctx;
556  return get_best_header(fpc, poutbuf, poutbuf_size);
557 
558  /* If a best_header was found last call remove it with the buffer data. */
559  if (fpc->best_header && fpc->best_header->best_child) {
561  FLACHeaderMarker *best_child = fpc->best_header->best_child;
562 
563  /* Remove headers in list until the end of the best_header. */
564  for (curr = fpc->headers; curr != best_child; curr = temp) {
565  if (curr != fpc->best_header) {
566  av_log(avctx, AV_LOG_DEBUG,
567  "dropping low score %i frame header from offset %i to %i\n",
568  curr->max_score, curr->offset, curr->next->offset);
569  }
570  temp = curr->next;
571  av_free(curr);
572  fpc->nb_headers_buffered--;
573  }
574  /* Release returned data from ring buffer. */
575  av_fifo_drain(fpc->fifo_buf, best_child->offset);
576 
577  /* Fix the offset for the headers remaining to match the new buffer. */
578  for (curr = best_child->next; curr; curr = curr->next)
579  curr->offset -= best_child->offset;
580 
581  best_child->offset = 0;
582  best_child->prev = NULL;
583  fpc->headers = best_child;
585  fpc->best_header = best_child;
586  return get_best_header(fpc, poutbuf, poutbuf_size);
587  }
588  fpc->best_header = NULL;
589  } else if (fpc->best_header) {
590  /* No end frame no need to delete the buffer; probably eof */
592 
593  for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {
594  temp = curr->next;
595  av_free(curr);
596  fpc->nb_headers_buffered--;
597  }
598  fpc->headers = fpc->best_header->next;
599  if (fpc->headers)
600  fpc->headers->prev = NULL;
601  av_freep(&fpc->best_header);
602  fpc->nb_headers_buffered--;
603  }
604 
605  /* Find and score new headers. */
606  /* buf_size is zero when flushing, so check for this since we do */
607  /* not want to try to read more input once we have found the end. */
608  /* Also note that buf can't be NULL. */
609  while ((buf_size && read_end < buf + buf_size &&
611  || (!buf_size && !fpc->end_padded)) {
612  int start_offset;
613 
614  /* Pad the end once if EOF, to check the final region for headers. */
615  if (!buf_size) {
616  fpc->end_padded = 1;
617  read_end = read_start + MAX_FRAME_HEADER_SIZE;
618  } else {
619  /* The maximum read size is the upper-bound of what the parser
620  needs to have the required number of frames buffered */
621  int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;
622  read_end = read_end + FFMIN(buf + buf_size - read_end,
623  nb_desired * FLAC_AVG_FRAME_SIZE);
624  }
625 
626  if (!av_fifo_space(fpc->fifo_buf) &&
628  fpc->nb_headers_buffered * 20) {
629  /* There is less than one valid flac header buffered for 20 headers
630  * buffered. Therefore the fifo is most likely filled with invalid
631  * data and the input is not a flac file. */
632  goto handle_error;
633  }
634 
635  /* Fill the buffer. */
636  if ( av_fifo_space(fpc->fifo_buf) < read_end - read_start
637  && av_fifo_realloc2(fpc->fifo_buf, (read_end - read_start) + 2*av_fifo_size(fpc->fifo_buf)) < 0) {
638  av_log(avctx, AV_LOG_ERROR,
639  "couldn't reallocate buffer of size %"PTRDIFF_SPECIFIER"\n",
640  (read_end - read_start) + av_fifo_size(fpc->fifo_buf));
641  goto handle_error;
642  }
643 
644  if (buf_size) {
645  av_fifo_generic_write(fpc->fifo_buf, (void*) read_start,
646  read_end - read_start, NULL);
647  } else {
648  int8_t pad[MAX_FRAME_HEADER_SIZE] = { 0 };
649  av_fifo_generic_write(fpc->fifo_buf, pad, sizeof(pad), NULL);
650  }
651 
652  /* Tag headers and update sequences. */
653  start_offset = av_fifo_size(fpc->fifo_buf) -
654  ((read_end - read_start) + (MAX_FRAME_HEADER_SIZE - 1));
655  start_offset = FFMAX(0, start_offset);
656  nb_headers = find_new_headers(fpc, start_offset);
657 
658  if (nb_headers < 0) {
659  av_log(avctx, AV_LOG_ERROR,
660  "find_new_headers couldn't allocate FLAC header\n");
661  goto handle_error;
662  }
663 
664  fpc->nb_headers_buffered = nb_headers;
665  /* Wait till FLAC_MIN_HEADERS to output a valid frame. */
666  if (!fpc->end_padded && fpc->nb_headers_buffered < FLAC_MIN_HEADERS) {
667  if (read_end < buf + buf_size) {
668  read_start = read_end;
669  continue;
670  } else {
671  goto handle_error;
672  }
673  }
674 
675  /* If headers found, update the scores since we have longer chains. */
676  if (fpc->end_padded || fpc->nb_headers_found)
677  score_sequences(fpc);
678 
679  /* restore the state pre-padding */
680  if (fpc->end_padded) {
681  int warp = fpc->fifo_buf->wptr - fpc->fifo_buf->buffer < MAX_FRAME_HEADER_SIZE;
682  /* HACK: drain the tail of the fifo */
685  if (warp) {
686  fpc->fifo_buf->wptr += fpc->fifo_buf->end -
687  fpc->fifo_buf->buffer;
688  }
689  read_start = read_end = NULL;
690  }
691  }
692 
693  for (curr = fpc->headers; curr; curr = curr->next) {
694  if (!fpc->best_header || curr->max_score > fpc->best_header->max_score) {
695  fpc->best_header = curr;
696  }
697  }
698 
699  if (fpc->best_header && fpc->best_header->max_score <= 0) {
700  // Only accept a bad header if there is no other option to continue
701  if (!buf_size || read_end != buf || fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
702  fpc->best_header = NULL;
703  }
704 
705  if (fpc->best_header) {
706  fpc->best_header_valid = 1;
707  if (fpc->best_header->offset > 0) {
708  /* Output a junk frame. */
709  av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",
710  fpc->best_header->offset);
711 
712  /* Set duration to 0. It is unknown or invalid in a junk frame. */
713  s->duration = 0;
714  *poutbuf_size = fpc->best_header->offset;
715  *poutbuf = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,
716  &fpc->wrap_buf,
718  return buf_size ? (read_end - buf) : (fpc->best_header->offset -
719  av_fifo_size(fpc->fifo_buf));
720  }
721  if (!buf_size)
722  return get_best_header(fpc, poutbuf, poutbuf_size);
723  }
724 
725 handle_error:
726  *poutbuf = NULL;
727  *poutbuf_size = 0;
728  return buf_size ? read_end - buf : 0;
729 }
730 
732 {
733  FLACParseContext *fpc = c->priv_data;
734  fpc->pc = c;
735  /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
736  it drains. This is allocated early to avoid slow reallocation. */
738  if (!fpc->fifo_buf) {
739  av_log(fpc->avctx, AV_LOG_ERROR,
740  "couldn't allocate fifo_buf\n");
741  return AVERROR(ENOMEM);
742  }
743  return 0;
744 }
745 
747 {
748  FLACParseContext *fpc = c->priv_data;
749  FLACHeaderMarker *curr = fpc->headers, *temp;
750 
751  while (curr) {
752  temp = curr->next;
753  av_free(curr);
754  curr = temp;
755  }
756  fpc->headers = NULL;
757  av_fifo_freep(&fpc->fifo_buf);
758  av_freep(&fpc->wrap_buf);
759 }
760 
763  .priv_data_size = sizeof(FLACParseContext),
764  .parser_init = flac_parse_init,
765  .parser_parse = flac_parse,
766  .parser_close = flac_parse_close,
767 };
#define wrap(func)
Definition: neontest.h:65
Macro definitions for various function/variable attributes.
#define av_cold
Definition: attributes.h:88
uint8_t
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
#define PARSER_FLAG_USE_CODEC_TS
Definition: avcodec.h:3419
#define PARSER_FLAG_COMPLETE_FRAMES
Definition: avcodec.h:3415
#define AV_RB16
Definition: intreadwrite.h:53
#define s(width, name)
Definition: cbs_vp9.c:257
#define f(width, name)
Definition: cbs_vp9.c:255
#define FFMIN(a, b)
Definition: common.h:105
#define FFMAX(a, b)
Definition: common.h:103
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
Public header for CRC hash function implementation.
a very simple circular buffer FIFO implementation
int ff_flac_decode_frame_header(AVCodecContext *avctx, GetBitContext *gb, FLACFrameInfo *fi, int log_level_offset)
Validate and decode a frame header.
Definition: flac.c:50
void ff_flac_set_channel_layout(AVCodecContext *avctx)
Definition: flac.c:196
FLAC (Free Lossless Audio Codec) decoder/demuxer common functions.
static uint8_t * flac_fifo_read(FLACParseContext *fpc, int offset, int *len)
Return a pointer in the fifo buffer where the offset starts at until the wrap point or end of request...
Definition: flac_parser.c:159
static void score_sequences(FLACParseContext *fpc)
Definition: flac_parser.c:460
#define FLAC_HEADER_CHANGED_PENALTY
Definition: flac_parser.c:51
#define FLAC_MAX_SEQUENTIAL_HEADERS
maximum number of adjacent headers that compare CRCs against each other
Definition: flac_parser.c:43
static void flac_parse_close(AVCodecParserContext *c)
Definition: flac_parser.c:746
static av_cold int flac_parse_init(AVCodecParserContext *c)
Definition: flac_parser.c:731
static int find_headers_search_validate(FLACParseContext *fpc, int offset)
Definition: flac_parser.c:170
static int score_header(FLACParseContext *fpc, FLACHeaderMarker *header)
Score a header.
Definition: flac_parser.c:420
#define FLAC_HEADER_NOT_SCORED_YET
Definition: flac_parser.c:54
static int check_header_mismatch(FLACParseContext *fpc, FLACHeaderMarker *header, FLACHeaderMarker *child, int log_level_offset)
Definition: flac_parser.c:310
static uint8_t * flac_fifo_read_wrap(FLACParseContext *fpc, int offset, int len, uint8_t **wrap_buf, int *allocated_size)
Non-destructive fast fifo pointer fetching Returns a pointer from the specified offset.
Definition: flac_parser.c:119
#define FLAC_HEADER_BASE_SCORE
scoring settings for score_header
Definition: flac_parser.c:50
#define FLAC_AVG_FRAME_SIZE
estimate for average size of a FLAC frame
Definition: flac_parser.c:47
#define MAX_FRAME_VERIFY_SIZE
Definition: flac_parser.c:58
#define FLAC_HEADER_NOT_PENALIZED_YET
Definition: flac_parser.c:53
static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf, FLACFrameInfo *fi)
Definition: flac_parser.c:98
static int check_header_fi_mismatch(FLACParseContext *fpc, FLACFrameInfo *header_fi, FLACFrameInfo *child_fi, int log_level_offset)
Definition: flac_parser.c:280
static int find_headers_search(FLACParseContext *fpc, uint8_t *buf, int buf_size, int search_start)
Definition: flac_parser.c:209
#define MAX_FRAME_HEADER_SIZE
largest possible size of flac header
Definition: flac_parser.c:57
AVCodecParser ff_flac_parser
Definition: flac_parser.c:761
#define FLAC_HEADER_CRC_FAIL_PENALTY
Definition: flac_parser.c:52
static int get_best_header(FLACParseContext *fpc, const uint8_t **poutbuf, int *poutbuf_size)
Definition: flac_parser.c:480
static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size)
Definition: flac_parser.c:527
#define FLAC_MIN_HEADERS
minimum number of headers buffered and checked before returning frames
Definition: flac_parser.c:45
static int find_new_headers(FLACParseContext *fpc, int search_start)
Definition: flac_parser.c:236
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition: get_bits.h:659
@ AV_CODEC_ID_FLAC
Definition: codec_id.h:436
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition: avcodec.h:215
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:374
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:394
@ AV_CRC_16_ANSI
Definition: crc.h:51
#define AVERROR(e)
Definition: error.h:43
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:215
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition: mem.c:478
int i
Definition: input.c:407
#define AV_RN32(p)
Definition: intreadwrite.h:364
void av_fifo_drain(AVFifoBuffer *f, int size)
Discard data from the FIFO.
Definition: fifo.c:233
void av_fifo_freep(AVFifoBuffer **f)
Free an AVFifoBuffer and reset pointer to NULL.
Definition: fifo.c:63
int av_fifo_size(const AVFifoBuffer *f)
Return the amount of data in bytes in the AVFifoBuffer, that is the amount of data you can read from ...
Definition: fifo.c:77
int av_fifo_space(const AVFifoBuffer *f)
Return the amount of space in bytes in the AVFifoBuffer, that is the amount of data you can write int...
Definition: fifo.c:82
AVFifoBuffer * av_fifo_alloc_array(size_t nmemb, size_t size)
Initialize an AVFifoBuffer.
Definition: fifo.c:49
int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int(*func)(void *, void *, int))
Feed data from a user-supplied callback to an AVFifoBuffer.
Definition: fifo.c:122
int av_fifo_realloc2(AVFifoBuffer *f, unsigned int new_size)
Resize an AVFifoBuffer.
Definition: fifo.c:87
#define PTRDIFF_SPECIFIER
Definition: internal.h:192
static const uint8_t header[24]
Definition: sdr2.c:67
main external API structure.
Definition: avcodec.h:536
int sample_rate
samples per second
Definition: avcodec.h:1196
int channels
number of audio channels
Definition: avcodec.h:1197
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:1247
int duration
Duration of the current frame.
Definition: avcodec.h:3503
int codec_ids[5]
Definition: avcodec.h:3549
uint8_t * wptr
Definition: fifo.h:33
uint8_t * buffer
Definition: fifo.h:32
uint32_t wndx
Definition: fifo.h:34
uint8_t * end
Definition: fifo.h:33
int is_var_size
specifies if the stream uses variable block sizes or a fixed block size; also determines the meaning ...
Definition: flac.h:89
int64_t frame_or_sample_num
frame number or sample number
Definition: flac.h:88
FLACCOMMONINFO int blocksize
block size of the frame
Definition: flac.h:86
int link_penalty[FLAC_MAX_SEQUENTIAL_HEADERS]
array of local scores between this header and the one at a distance equal array position
Definition: flac_parser.c:62
int max_score
maximum score found after checking each child that has a valid CRC
Definition: flac_parser.c:65
FLACFrameInfo fi
decoded frame header info
Definition: flac_parser.c:67
struct FLACHeaderMarker * best_child
following frame header with which this frame has the best score with
Definition: flac_parser.c:73
struct FLACHeaderMarker * prev
CRC-8 verified header that immediately precedes this one
Definition: flac_parser.c:71
struct FLACHeaderMarker * next
next CRC-8 verified header that immediately follows this one in the bytestream
Definition: flac_parser.c:68
int offset
byte offset from start of FLACParseContext->buffer
Definition: flac_parser.c:61
uint8_t * wrap_buf
general fifo read buffer when wrapped
Definition: flac_parser.c:92
FLACHeaderMarker * headers
linked-list that starts at the first CRC-8 verified header within buffer
Definition: flac_parser.c:81
int last_fi_valid
set if last_fi is valid
Definition: flac_parser.c:95
FLACFrameInfo last_fi
last decoded frame header info
Definition: flac_parser.c:94
AVCodecContext * avctx
codec context pointer for logging
Definition: flac_parser.c:80
FLACHeaderMarker * best_header
highest scoring header within buffer
Definition: flac_parser.c:83
int nb_headers_buffered
number of headers that are buffered
Definition: flac_parser.c:86
AVFifoBuffer * fifo_buf
buffer to store all data until headers can be verified
Definition: flac_parser.c:89
int end_padded
specifies if fifo_buf's end is padded
Definition: flac_parser.c:91
int best_header_valid
flag set when the parser returns junk; if set return best_header next time
Definition: flac_parser.c:87
AVCodecParserContext * pc
parent context
Definition: flac_parser.c:79
int nb_headers_found
number of headers found in the last flac_parse() call
Definition: flac_parser.c:84
int wrap_buf_allocated_size
actual allocated size of the buffer
Definition: flac_parser.c:93
#define av_free(p)
#define av_freep(p)
#define av_log(a,...)
int size
else temp
Definition: vf_mcdeint.c:259
static const uint8_t offset[127][2]
Definition: vf_spp.c:107
int len
static double c[64]