3 * Copyright (c) 2010 Michael Chinen
5 * This file is part of FFmpeg.
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.
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.
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
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.
35 #include "libavutil/attributes.h"
36 #include "libavutil/crc.h"
37 #include "bytestream.h"
41 /** maximum number of adjacent headers that compare CRCs against each other */
42 #define FLAC_MAX_SEQUENTIAL_HEADERS 4
43 /** minimum number of headers buffered and checked before returning frames */
44 #define FLAC_MIN_HEADERS 10
45 /** estimate for average size of a FLAC frame */
46 #define FLAC_AVG_FRAME_SIZE 8192
48 /** scoring settings for score_header */
49 #define FLAC_HEADER_BASE_SCORE 10
50 #define FLAC_HEADER_CHANGED_PENALTY 7
51 #define FLAC_HEADER_CRC_FAIL_PENALTY 50
52 #define FLAC_HEADER_NOT_PENALIZED_YET 100000
53 #define FLAC_HEADER_NOT_SCORED_YET -100000
55 /** largest possible size of flac header */
56 #define MAX_FRAME_HEADER_SIZE 16
57 #define MAX_FRAME_VERIFY_SIZE (MAX_FRAME_HEADER_SIZE + 1)
59 typedef struct FifoBuffer
{
67 typedef struct FLACHeaderMarker
{
68 int offset
; /**< byte offset from start of FLACParseContext->buffer */
69 int link_penalty
[FLAC_MAX_SEQUENTIAL_HEADERS
]; /**< array of local scores
70 between this header and the one at a distance equal
72 int max_score
; /**< maximum score found after checking each child that
74 FLACFrameInfo fi
; /**< decoded frame header info */
75 struct FLACHeaderMarker
*next
; /**< next CRC-8 verified header that
76 immediately follows this one in
78 struct FLACHeaderMarker
*best_child
; /**< following frame header with
79 which this frame has the best
83 typedef struct FLACParseContext
{
84 AVCodecParserContext
*pc
; /**< parent context */
85 AVCodecContext
*avctx
; /**< codec context pointer for logging */
86 FLACHeaderMarker
*headers
; /**< linked-list that starts at the first
87 CRC-8 verified header within buffer */
88 FLACHeaderMarker
*best_header
; /**< highest scoring header within buffer */
89 int nb_headers_found
; /**< number of headers found in the last
91 int nb_headers_buffered
; /**< number of headers that are buffered */
92 int best_header_valid
; /**< flag set when the parser returns junk;
93 if set return best_header next time */
94 FifoBuffer fifo_buf
; /**< buffer to store all data until headers
96 int end_padded
; /**< specifies if fifo_buf's end is padded */
97 uint8_t *wrap_buf
; /**< general fifo read buffer when wrapped */
98 int wrap_buf_allocated_size
; /**< actual allocated size of the buffer */
99 FLACFrameInfo last_fi
; /**< last decoded frame header info */
100 int last_fi_valid
; /**< set if last_fi is valid */
103 static int frame_header_is_valid(AVCodecContext
*avctx
, const uint8_t *buf
,
107 uint8_t subframe_type
;
109 // header plus one byte from first subframe
110 init_get_bits(&gb
, buf
, MAX_FRAME_VERIFY_SIZE
* 8);
111 if (ff_flac_decode_frame_header(avctx
, &gb
, fi
, 127)) {
115 if (get_bits1(&gb
) != 0) {
119 // 000000 : SUBFRAME_CONSTANT
120 // 000001 : SUBFRAME_VERBATIM
123 // 001xxx : if(xxx <= 4) SUBFRAME_FIXED, xxx=order ; else reserved
125 // 1xxxxx : SUBFRAME_LPC, xxxxx=order-1
126 subframe_type
= get_bits(&gb
, 6);
127 if (!(subframe_type
== 0 ||
128 subframe_type
== 1 ||
129 ((subframe_type
>= 8) && (subframe_type
<= 12)) ||
130 (subframe_type
>= 32))) {
137 static size_t flac_fifo_size(const FifoBuffer
*f
)
139 if (f
->wptr
<= f
->rptr
&& !f
->empty
)
140 return (f
->wptr
- f
->buffer
) + (f
->end
- f
->rptr
);
141 return f
->wptr
- f
->rptr
;
144 static size_t flac_fifo_space(const FifoBuffer
*f
)
146 return f
->end
- f
->buffer
- flac_fifo_size(f
);
150 * Non-destructive fast fifo pointer fetching
151 * Returns a pointer from the specified offset.
152 * If possible the pointer points within the fifo buffer.
153 * Otherwise (if it would cause a wrap around,) a pointer to a user-specified
155 * The pointer can be NULL. In any case it will be reallocated to hold the size.
156 * If the returned pointer will be used after subsequent calls to flac_fifo_read_wrap
157 * then the subsequent calls should pass in a different wrap_buf so as to not
158 * overwrite the contents of the previous wrap_buf.
159 * This function is based on av_fifo_generic_read, which is why there is a comment
160 * about a memory barrier for SMP.
162 static uint8_t *flac_fifo_read_wrap(FLACParseContext
*fpc
, int offset
, int len
,
163 uint8_t **wrap_buf
, int *allocated_size
)
165 FifoBuffer
*f
= &fpc
->fifo_buf
;
166 uint8_t *start
= f
->rptr
+ offset
;
170 start
-= f
->end
- f
->buffer
;
171 if (f
->end
- start
>= len
)
174 tmp_buf
= av_fast_realloc(*wrap_buf
, allocated_size
, len
);
177 av_log(fpc
->avctx
, AV_LOG_ERROR
,
178 "couldn't reallocate wrap buffer of size %d", len
);
183 int seg_len
= FFMIN(f
->end
- start
, len
);
184 memcpy(tmp_buf
, start
, seg_len
);
185 tmp_buf
= (uint8_t*)tmp_buf
+ seg_len
;
186 // memory barrier needed for SMP here in theory
188 start
+= seg_len
- (f
->end
- f
->buffer
);
196 * Return a pointer in the fifo buffer where the offset starts at until
197 * the wrap point or end of request.
198 * len will contain the valid length of the returned buffer.
199 * A second call to flac_fifo_read (with new offset and len) should be called
200 * to get the post-wrap buf if the returned len is less than the requested.
202 static uint8_t *flac_fifo_read(FifoBuffer
*f
, int offset
, int *len
)
204 uint8_t *start
= f
->rptr
+ offset
;
207 start
-= f
->end
- f
->buffer
;
208 *len
= FFMIN(*len
, f
->end
- start
);
212 static int flac_fifo_grow(FifoBuffer
*f
, size_t inc
)
214 size_t size_old
= f
->end
- f
->buffer
;
215 size_t offset_r
= f
->rptr
- f
->buffer
;
216 size_t offset_w
= f
->wptr
- f
->buffer
;
221 if (size_old
> SIZE_MAX
- inc
)
222 return AVERROR(EINVAL
);
223 size_new
= size_old
+ inc
;
225 tmp
= av_realloc(f
->buffer
, size_new
);
227 return AVERROR(ENOMEM
);
229 // move the data from the beginning of the ring buffer
230 // to the newly allocated space
231 if (offset_w
<= offset_r
&& !f
->empty
) {
232 const size_t copy
= FFMIN(inc
, offset_w
);
233 memcpy(tmp
+ size_old
, tmp
, copy
);
234 if (copy
< offset_w
) {
235 memmove(tmp
, tmp
+ copy
, offset_w
- copy
);
238 offset_w
= size_old
+ copy
;
242 f
->end
= f
->buffer
+ size_new
;
243 f
->rptr
= f
->buffer
+ offset_r
;
244 f
->wptr
= f
->buffer
+ offset_w
;
249 static int flac_fifo_write(FifoBuffer
*f
, const uint8_t *src
, size_t size
)
253 if (flac_fifo_space(f
) < size
) {
254 int ret
= flac_fifo_grow(f
, FFMAX(flac_fifo_size(f
), size
));
264 size_t len
= FFMIN(f
->end
- wptr
, size
);
265 memcpy(wptr
, src
, len
);
278 static void flac_fifo_drain(FifoBuffer
*f
, size_t size
)
280 size_t size_cur
= flac_fifo_size(f
);
282 av_assert0(size_cur
>= size
);
283 if (size_cur
== size
)
287 if (f
->rptr
>= f
->end
)
288 f
->rptr
-= f
->end
- f
->buffer
;
291 static int flac_fifo_alloc(FifoBuffer
*f
, size_t size
)
293 memset(f
, 0, sizeof(*f
));
295 f
->buffer
= av_realloc(NULL
, size
);
297 return AVERROR(ENOMEM
);
301 f
->end
= f
->buffer
+ size
;
308 static void flac_fifo_free(FifoBuffer
*f
)
310 av_freep(&f
->buffer
);
311 memset(f
, 0, sizeof(*f
));
314 static int find_headers_search_validate(FLACParseContext
*fpc
, int offset
)
319 header_buf
= flac_fifo_read_wrap(fpc
, offset
,
320 MAX_FRAME_VERIFY_SIZE
+ AV_INPUT_BUFFER_PADDING_SIZE
,
322 &fpc
->wrap_buf_allocated_size
);
323 if (frame_header_is_valid(fpc
->avctx
, header_buf
, &fi
)) {
324 FLACHeaderMarker
**end_handle
= &fpc
->headers
;
328 while (*end_handle
) {
329 end_handle
= &(*end_handle
)->next
;
333 *end_handle
= av_mallocz(sizeof(**end_handle
));
335 av_log(fpc
->avctx
, AV_LOG_ERROR
,
336 "couldn't allocate FLACHeaderMarker\n");
337 return AVERROR(ENOMEM
);
339 (*end_handle
)->fi
= fi
;
340 (*end_handle
)->offset
= offset
;
342 for (i
= 0; i
< FLAC_MAX_SEQUENTIAL_HEADERS
; i
++)
343 (*end_handle
)->link_penalty
[i
] = FLAC_HEADER_NOT_PENALIZED_YET
;
345 fpc
->nb_headers_found
++;
351 static int find_headers_search(FLACParseContext
*fpc
, uint8_t *buf
,
352 int buf_size
, int search_start
)
354 int size
= 0, mod_offset
= (buf_size
- 1) % 4, i
, j
;
357 for (i
= 0; i
< mod_offset
; i
++) {
358 if ((AV_RB16(buf
+ i
) & 0xFFFE) == 0xFFF8) {
359 int ret
= find_headers_search_validate(fpc
, search_start
+ i
);
360 size
= FFMAX(size
, ret
);
364 for (; i
< buf_size
- 1; i
+= 4) {
365 x
= AV_RN32(buf
+ i
);
366 if (((x
& ~(x
+ 0x01010101)) & 0x80808080)) {
367 for (j
= 0; j
< 4; j
++) {
368 if ((AV_RB16(buf
+ i
+ j
) & 0xFFFE) == 0xFFF8) {
369 int ret
= find_headers_search_validate(fpc
, search_start
+ i
+ j
);
370 size
= FFMAX(size
, ret
);
378 static int find_new_headers(FLACParseContext
*fpc
, int search_start
)
380 FLACHeaderMarker
*end
;
381 int search_end
, size
= 0, read_len
, temp
;
383 fpc
->nb_headers_found
= 0;
385 /* Search for a new header of at most 16 bytes. */
386 search_end
= flac_fifo_size(&fpc
->fifo_buf
) - (MAX_FRAME_HEADER_SIZE
- 1);
387 read_len
= search_end
- search_start
+ 1;
388 buf
= flac_fifo_read(&fpc
->fifo_buf
, search_start
, &read_len
);
389 size
= find_headers_search(fpc
, buf
, read_len
, search_start
);
390 search_start
+= read_len
- 1;
392 /* If fifo end was hit do the wrap around. */
393 if (search_start
!= search_end
) {
396 wrap
[0] = buf
[read_len
- 1];
397 /* search_start + 1 is the post-wrap offset in the fifo. */
398 read_len
= search_end
- (search_start
+ 1) + 1;
400 buf
= flac_fifo_read(&fpc
->fifo_buf
, search_start
+ 1, &read_len
);
403 if ((AV_RB16(wrap
) & 0xFFFE) == 0xFFF8) {
404 temp
= find_headers_search_validate(fpc
, search_start
);
405 size
= FFMAX(size
, temp
);
409 /* Continue to do the last half of the wrap. */
410 temp
= find_headers_search(fpc
, buf
, read_len
, search_start
);
411 size
= FFMAX(size
, temp
);
412 search_start
+= read_len
- 1;
415 /* Return the size even if no new headers were found. */
416 if (!size
&& fpc
->headers
)
417 for (end
= fpc
->headers
; end
; end
= end
->next
)
422 static int check_header_fi_mismatch(FLACParseContext
*fpc
,
423 FLACFrameInfo
*header_fi
,
424 FLACFrameInfo
*child_fi
,
425 int log_level_offset
)
428 if (child_fi
->samplerate
!= header_fi
->samplerate
) {
429 deduction
+= FLAC_HEADER_CHANGED_PENALTY
;
430 av_log(fpc
->avctx
, AV_LOG_WARNING
+ log_level_offset
,
431 "sample rate change detected in adjacent frames\n");
433 if (child_fi
->bps
!= header_fi
->bps
) {
434 deduction
+= FLAC_HEADER_CHANGED_PENALTY
;
435 av_log(fpc
->avctx
, AV_LOG_WARNING
+ log_level_offset
,
436 "bits per sample change detected in adjacent frames\n");
438 if (child_fi
->is_var_size
!= header_fi
->is_var_size
) {
439 /* Changing blocking strategy not allowed per the spec */
440 deduction
+= FLAC_HEADER_BASE_SCORE
;
441 av_log(fpc
->avctx
, AV_LOG_WARNING
+ log_level_offset
,
442 "blocking strategy change detected in adjacent frames\n");
444 if (child_fi
->channels
!= header_fi
->channels
) {
445 deduction
+= FLAC_HEADER_CHANGED_PENALTY
;
446 av_log(fpc
->avctx
, AV_LOG_WARNING
+ log_level_offset
,
447 "number of channels change detected in adjacent frames\n");
452 static int check_header_mismatch(FLACParseContext
*fpc
,
453 FLACHeaderMarker
*header
,
454 FLACHeaderMarker
*child
,
455 int log_level_offset
)
457 FLACFrameInfo
*header_fi
= &header
->fi
, *child_fi
= &child
->fi
;
458 int deduction
, deduction_expected
= 0, i
;
459 deduction
= check_header_fi_mismatch(fpc
, header_fi
, child_fi
,
461 /* Check sample and frame numbers. */
462 if ((child_fi
->frame_or_sample_num
- header_fi
->frame_or_sample_num
463 != header_fi
->blocksize
) &&
464 (child_fi
->frame_or_sample_num
465 != header_fi
->frame_or_sample_num
+ 1)) {
466 FLACHeaderMarker
*curr
;
467 int64_t expected_frame_num
, expected_sample_num
;
468 /* If there are frames in the middle we expect this deduction,
469 as they are probably valid and this one follows it */
471 expected_frame_num
= expected_sample_num
= header_fi
->frame_or_sample_num
;
473 while (curr
!= child
) {
474 /* Ignore frames that failed all crc checks */
475 for (i
= 0; i
< FLAC_MAX_SEQUENTIAL_HEADERS
; i
++) {
476 if (curr
->link_penalty
[i
] < FLAC_HEADER_CRC_FAIL_PENALTY
) {
477 expected_frame_num
++;
478 expected_sample_num
+= curr
->fi
.blocksize
;
485 if (expected_frame_num
== child_fi
->frame_or_sample_num
||
486 expected_sample_num
== child_fi
->frame_or_sample_num
)
487 deduction_expected
= deduction
? 0 : 1;
489 deduction
+= FLAC_HEADER_CHANGED_PENALTY
;
490 av_log(fpc
->avctx
, AV_LOG_WARNING
+ log_level_offset
,
491 "sample/frame number mismatch in adjacent frames\n");
494 /* If we have suspicious headers, check the CRC between them */
495 if (deduction
&& !deduction_expected
) {
496 FLACHeaderMarker
*curr
;
500 int inverted_test
= 0;
502 /* Since CRC is expensive only do it if we haven't yet.
503 This assumes a CRC penalty is greater than all other check penalties */
505 for (i
= 0; i
< FLAC_MAX_SEQUENTIAL_HEADERS
&& curr
!= child
; i
++)
508 av_assert0(i
< FLAC_MAX_SEQUENTIAL_HEADERS
);
510 if (header
->link_penalty
[i
] < FLAC_HEADER_CRC_FAIL_PENALTY
||
511 header
->link_penalty
[i
] == FLAC_HEADER_NOT_PENALIZED_YET
) {
512 FLACHeaderMarker
*start
, *end
;
514 /* Although overlapping chains are scored, the crc should never
515 have to be computed twice for a single byte. */
519 header
->link_penalty
[i
- 1] >= FLAC_HEADER_CRC_FAIL_PENALTY
) {
520 while (start
->next
!= child
)
524 header
->next
->link_penalty
[i
-1] >=
525 FLAC_HEADER_CRC_FAIL_PENALTY
) {
530 read_len
= end
->offset
- start
->offset
;
531 buf
= flac_fifo_read(&fpc
->fifo_buf
, start
->offset
, &read_len
);
532 crc
= av_crc(av_crc_get_table(AV_CRC_16_ANSI
), 0, buf
, read_len
);
533 read_len
= (end
->offset
- start
->offset
) - read_len
;
536 buf
= flac_fifo_read(&fpc
->fifo_buf
, end
->offset
- read_len
, &read_len
);
537 crc
= av_crc(av_crc_get_table(AV_CRC_16_ANSI
), crc
, buf
, read_len
);
541 if (!crc
^ !inverted_test
) {
542 deduction
+= FLAC_HEADER_CRC_FAIL_PENALTY
;
543 av_log(fpc
->avctx
, AV_LOG_WARNING
+ log_level_offset
,
544 "crc check failed from offset %i (frame %"PRId64
") to %i (frame %"PRId64
")\n",
545 header
->offset
, header_fi
->frame_or_sample_num
,
546 child
->offset
, child_fi
->frame_or_sample_num
);
555 * Give FLAC_HEADER_BASE_SCORE points to a frame for existing.
556 * If it has children, (subsequent frames of which the preceding CRC footer
557 * validates against this one,) then take the maximum score of the children,
558 * with a penalty of FLAC_HEADER_CHANGED_PENALTY applied for each change to
559 * bps, sample rate, channels, but not decorrelation mode, or blocksize,
560 * because it can change often.
562 static int score_header(FLACParseContext
*fpc
, FLACHeaderMarker
*header
)
564 FLACHeaderMarker
*child
;
567 int base_score
= FLAC_HEADER_BASE_SCORE
;
568 if (header
->max_score
!= FLAC_HEADER_NOT_SCORED_YET
)
569 return header
->max_score
;
571 /* Modify the base score with changes from the last output header */
572 if (fpc
->last_fi_valid
) {
573 /* Silence the log since this will be repeated if selected */
574 base_score
-= check_header_fi_mismatch(fpc
, &fpc
->last_fi
, &header
->fi
,
578 header
->max_score
= base_score
;
580 /* Check and compute the children's scores. */
581 child
= header
->next
;
582 for (dist
= 0; dist
< FLAC_MAX_SEQUENTIAL_HEADERS
&& child
; dist
++) {
583 /* Look at the child's frame header info and penalize suspicious
584 changes between the headers. */
585 if (header
->link_penalty
[dist
] == FLAC_HEADER_NOT_PENALIZED_YET
) {
586 header
->link_penalty
[dist
] = check_header_mismatch(fpc
, header
,
587 child
, AV_LOG_DEBUG
);
589 child_score
= score_header(fpc
, child
) - header
->link_penalty
[dist
];
591 if (FLAC_HEADER_BASE_SCORE
+ child_score
> header
->max_score
) {
592 /* Keep the child because the frame scoring is dynamic. */
593 header
->best_child
= child
;
594 header
->max_score
= base_score
+ child_score
;
599 return header
->max_score
;
602 static void score_sequences(FLACParseContext
*fpc
)
604 FLACHeaderMarker
*curr
;
605 int best_score
= 0;//FLAC_HEADER_NOT_SCORED_YET;
606 /* First pass to clear all old scores. */
607 for (curr
= fpc
->headers
; curr
; curr
= curr
->next
)
608 curr
->max_score
= FLAC_HEADER_NOT_SCORED_YET
;
610 /* Do a second pass to score them all. */
611 for (curr
= fpc
->headers
; curr
; curr
= curr
->next
) {
612 if (score_header(fpc
, curr
) > best_score
) {
613 fpc
->best_header
= curr
;
614 best_score
= curr
->max_score
;
619 static int get_best_header(FLACParseContext
*fpc
, const uint8_t **poutbuf
,
622 FLACHeaderMarker
*header
= fpc
->best_header
;
623 FLACHeaderMarker
*child
= header
->best_child
;
625 *poutbuf_size
= flac_fifo_size(&fpc
->fifo_buf
) - header
->offset
;
627 *poutbuf_size
= child
->offset
- header
->offset
;
629 /* If the child has suspicious changes, log them */
630 check_header_mismatch(fpc
, header
, child
, 0);
633 ff_flac_set_channel_layout(fpc
->avctx
, header
->fi
.channels
);
635 fpc
->avctx
->sample_rate
= header
->fi
.samplerate
;
636 fpc
->pc
->duration
= header
->fi
.blocksize
;
637 *poutbuf
= flac_fifo_read_wrap(fpc
, header
->offset
, *poutbuf_size
,
639 &fpc
->wrap_buf_allocated_size
);
641 if (fpc
->pc
->flags
& PARSER_FLAG_USE_CODEC_TS
) {
642 if (header
->fi
.is_var_size
)
643 fpc
->pc
->pts
= header
->fi
.frame_or_sample_num
;
644 else if (header
->best_child
)
645 fpc
->pc
->pts
= header
->fi
.frame_or_sample_num
* header
->fi
.blocksize
;
648 fpc
->best_header_valid
= 0;
649 fpc
->last_fi_valid
= 1;
650 fpc
->last_fi
= header
->fi
;
652 /* Return the negative overread index so the client can compute pos.
653 This should be the amount overread to the beginning of the child */
655 return child
->offset
- flac_fifo_size(&fpc
->fifo_buf
);
659 static int flac_parse(AVCodecParserContext
*s
, AVCodecContext
*avctx
,
660 const uint8_t **poutbuf
, int *poutbuf_size
,
661 const uint8_t *buf
, int buf_size
)
663 FLACParseContext
*fpc
= s
->priv_data
;
664 FLACHeaderMarker
*curr
;
666 const uint8_t *read_end
= buf
;
667 const uint8_t *read_start
= buf
;
669 if (s
->flags
& PARSER_FLAG_COMPLETE_FRAMES
) {
671 if (frame_header_is_valid(avctx
, buf
, &fi
)) {
672 s
->duration
= fi
.blocksize
;
673 if (!avctx
->sample_rate
)
674 avctx
->sample_rate
= fi
.samplerate
;
675 if (fpc
->pc
->flags
& PARSER_FLAG_USE_CODEC_TS
) {
676 fpc
->pc
->pts
= fi
.frame_or_sample_num
;
678 fpc
->pc
->pts
*= fi
.blocksize
;
682 *poutbuf_size
= buf_size
;
687 if (fpc
->best_header_valid
)
688 return get_best_header(fpc
, poutbuf
, poutbuf_size
);
690 /* If a best_header was found last call remove it with the buffer data. */
691 if (fpc
->best_header
&& fpc
->best_header
->best_child
) {
692 FLACHeaderMarker
*temp
;
693 FLACHeaderMarker
*best_child
= fpc
->best_header
->best_child
;
695 /* Remove headers in list until the end of the best_header. */
696 for (curr
= fpc
->headers
; curr
!= best_child
; curr
= temp
) {
697 if (curr
!= fpc
->best_header
) {
698 av_log(avctx
, AV_LOG_DEBUG
,
699 "dropping low score %i frame header from offset %i to %i\n",
700 curr
->max_score
, curr
->offset
, curr
->next
->offset
);
704 fpc
->nb_headers_buffered
--;
706 /* Release returned data from ring buffer. */
707 flac_fifo_drain(&fpc
->fifo_buf
, best_child
->offset
);
709 /* Fix the offset for the headers remaining to match the new buffer. */
710 for (curr
= best_child
->next
; curr
; curr
= curr
->next
)
711 curr
->offset
-= best_child
->offset
;
713 best_child
->offset
= 0;
714 fpc
->headers
= best_child
;
715 if (fpc
->nb_headers_buffered
>= FLAC_MIN_HEADERS
) {
716 fpc
->best_header
= best_child
;
717 return get_best_header(fpc
, poutbuf
, poutbuf_size
);
719 fpc
->best_header
= NULL
;
720 } else if (fpc
->best_header
) {
721 /* No end frame no need to delete the buffer; probably eof */
722 FLACHeaderMarker
*temp
;
724 for (curr
= fpc
->headers
; curr
!= fpc
->best_header
; curr
= temp
) {
727 fpc
->nb_headers_buffered
--;
729 fpc
->headers
= fpc
->best_header
->next
;
730 av_freep(&fpc
->best_header
);
731 fpc
->nb_headers_buffered
--;
734 /* Find and score new headers. */
735 /* buf_size is zero when flushing, so check for this since we do */
736 /* not want to try to read more input once we have found the end. */
737 /* Also note that buf can't be NULL. */
738 while ((buf_size
&& read_end
< buf
+ buf_size
&&
739 fpc
->nb_headers_buffered
< FLAC_MIN_HEADERS
)
740 || (!buf_size
&& !fpc
->end_padded
)) {
741 int start_offset
, ret
;
743 /* Pad the end once if EOF, to check the final region for headers. */
746 read_end
= read_start
+ MAX_FRAME_HEADER_SIZE
;
748 /* The maximum read size is the upper-bound of what the parser
749 needs to have the required number of frames buffered */
750 int nb_desired
= FLAC_MIN_HEADERS
- fpc
->nb_headers_buffered
+ 1;
751 read_end
= read_end
+ FFMIN(buf
+ buf_size
- read_end
,
752 nb_desired
* FLAC_AVG_FRAME_SIZE
);
755 if (!flac_fifo_space(&fpc
->fifo_buf
) &&
756 flac_fifo_size(&fpc
->fifo_buf
) / FLAC_AVG_FRAME_SIZE
>
757 fpc
->nb_headers_buffered
* 20) {
758 /* There is less than one valid flac header buffered for 20 headers
759 * buffered. Therefore the fifo is most likely filled with invalid
760 * data and the input is not a flac file. */
764 /* Fill the buffer. */
766 ret
= flac_fifo_write(&fpc
->fifo_buf
, read_start
,
767 read_end
- read_start
);
769 int8_t pad
[MAX_FRAME_HEADER_SIZE
] = { 0 };
770 ret
= flac_fifo_write(&fpc
->fifo_buf
, pad
, sizeof(pad
));
773 av_log(avctx
, AV_LOG_ERROR
, "Error buffering data\n");
777 /* Tag headers and update sequences. */
778 start_offset
= flac_fifo_size(&fpc
->fifo_buf
) -
779 ((read_end
- read_start
) + (MAX_FRAME_HEADER_SIZE
- 1));
780 start_offset
= FFMAX(0, start_offset
);
781 nb_headers
= find_new_headers(fpc
, start_offset
);
783 if (nb_headers
< 0) {
784 av_log(avctx
, AV_LOG_ERROR
,
785 "find_new_headers couldn't allocate FLAC header\n");
789 fpc
->nb_headers_buffered
= nb_headers
;
790 /* Wait till FLAC_MIN_HEADERS to output a valid frame. */
791 if (!fpc
->end_padded
&& fpc
->nb_headers_buffered
< FLAC_MIN_HEADERS
) {
792 if (read_end
< buf
+ buf_size
) {
793 read_start
= read_end
;
800 /* If headers found, update the scores since we have longer chains. */
801 if (fpc
->end_padded
|| fpc
->nb_headers_found
)
802 score_sequences(fpc
);
804 /* restore the state pre-padding */
805 if (fpc
->end_padded
) {
806 int empty
= flac_fifo_size(&fpc
->fifo_buf
) == MAX_FRAME_HEADER_SIZE
;
807 int warp
= fpc
->fifo_buf
.wptr
- fpc
->fifo_buf
.buffer
< MAX_FRAME_HEADER_SIZE
;
808 /* HACK: drain the tail of the fifo */
809 fpc
->fifo_buf
.wptr
-= MAX_FRAME_HEADER_SIZE
;
811 fpc
->fifo_buf
.wptr
+= fpc
->fifo_buf
.end
-
812 fpc
->fifo_buf
.buffer
;
814 fpc
->fifo_buf
.empty
= empty
;
815 read_start
= read_end
= NULL
;
819 for (curr
= fpc
->headers
; curr
; curr
= curr
->next
) {
820 if (!fpc
->best_header
|| curr
->max_score
> fpc
->best_header
->max_score
) {
821 fpc
->best_header
= curr
;
825 if (fpc
->best_header
&& fpc
->best_header
->max_score
<= 0) {
826 // Only accept a bad header if there is no other option to continue
827 if (!buf_size
|| read_end
!= buf
|| fpc
->nb_headers_buffered
< FLAC_MIN_HEADERS
)
828 fpc
->best_header
= NULL
;
831 if (fpc
->best_header
) {
832 fpc
->best_header_valid
= 1;
833 if (fpc
->best_header
->offset
> 0) {
834 /* Output a junk frame. */
835 av_log(avctx
, AV_LOG_DEBUG
, "Junk frame till offset %i\n",
836 fpc
->best_header
->offset
);
838 /* Set duration to 0. It is unknown or invalid in a junk frame. */
840 *poutbuf_size
= fpc
->best_header
->offset
;
841 *poutbuf
= flac_fifo_read_wrap(fpc
, 0, *poutbuf_size
,
843 &fpc
->wrap_buf_allocated_size
);
844 return buf_size
? (read_end
- buf
) : (fpc
->best_header
->offset
-
845 flac_fifo_size(&fpc
->fifo_buf
));
848 return get_best_header(fpc
, poutbuf
, poutbuf_size
);
854 return buf_size
? read_end
- buf
: 0;
857 static av_cold
int flac_parse_init(AVCodecParserContext
*c
)
859 FLACParseContext
*fpc
= c
->priv_data
;
863 /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
864 it drains. This is allocated early to avoid slow reallocation. */
865 ret
= flac_fifo_alloc(&fpc
->fifo_buf
, (FLAC_MIN_HEADERS
+ 3) * FLAC_AVG_FRAME_SIZE
);
867 av_log(fpc
->avctx
, AV_LOG_ERROR
,
868 "couldn't allocate fifo_buf\n");
869 return AVERROR(ENOMEM
);
874 static void flac_parse_close(AVCodecParserContext
*c
)
876 FLACParseContext
*fpc
= c
->priv_data
;
877 FLACHeaderMarker
*curr
= fpc
->headers
, *temp
;
885 flac_fifo_free(&fpc
->fifo_buf
);
886 av_freep(&fpc
->wrap_buf
);
889 const AVCodecParser ff_flac_parser
= {
890 .codec_ids
= { AV_CODEC_ID_FLAC
},
891 .priv_data_size
= sizeof(FLACParseContext
),
892 .parser_init
= flac_parse_init
,
893 .parser_parse
= flac_parse
,
894 .parser_close
= flac_parse_close
,