FFmpeg
Loading...
Searching...
No Matches
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
36#include "libavutil/crc.h"
38#include "libavutil/macros.h"
39#include "libavutil/mem.h"
40#include "flac.h"
41#include "flac_parse.h"
42#include "parser_internal.h"
43
44/** maximum number of adjacent headers that compare CRCs against each other */
45#define FLAC_MAX_SEQUENTIAL_HEADERS 4
46/** minimum number of headers buffered and checked before returning frames */
47#define FLAC_MIN_HEADERS 10
48/** estimate for average size of a FLAC frame */
49#define FLAC_AVG_FRAME_SIZE 8192
50
51/** scoring settings for score_header */
52#define FLAC_HEADER_BASE_SCORE 10
53#define FLAC_HEADER_CHANGED_PENALTY 7
54#define FLAC_HEADER_CRC_FAIL_PENALTY 50
55#define FLAC_HEADER_NOT_PENALIZED_YET 100000
56#define FLAC_HEADER_NOT_SCORED_YET -100000
57
58/** largest possible size of flac header */
59#define MAX_FRAME_HEADER_SIZE 16
60#define MAX_FRAME_VERIFY_SIZE (MAX_FRAME_HEADER_SIZE + 1)
61
62typedef struct FifoBuffer {
63 uint8_t *buffer;
64 uint8_t *end;
65 uint8_t *rptr;
66 uint8_t *wptr;
67 int empty;
69
70typedef struct FLACHeaderMarker {
71 int offset; /**< byte offset from start of FLACParseContext->buffer */
72 int link_penalty[FLAC_MAX_SEQUENTIAL_HEADERS]; /**< array of local scores
73 between this header and the one at a distance equal
74 array position */
75 int max_score; /**< maximum score found after checking each child that
76 has a valid CRC */
77 FLACFrameInfo fi; /**< decoded frame header info */
78 struct FLACHeaderMarker *next; /**< next CRC-8 verified header that
79 immediately follows this one in
80 the bytestream */
81 struct FLACHeaderMarker *prev; /**< CRC-8 verified header that
82 immediately precedes this one */
83 struct FLACHeaderMarker *best_child; /**< following frame header with
84 which this frame has the best
85 score with */
87
88typedef struct FLACParseContext {
89 AVCodecParserContext *pc; /**< parent context */
90 AVCodecContext *avctx; /**< codec context pointer for logging */
91 FLACHeaderMarker *headers; /**< linked-list that starts at the first
92 CRC-8 verified header within buffer */
93 FLACHeaderMarker *best_header; /**< highest scoring header within buffer */
94 int nb_headers_found; /**< number of headers found in the last
95 flac_parse() call */
96 int nb_headers_buffered; /**< number of headers that are buffered */
97 int best_header_valid; /**< flag set when the parser returns junk;
98 if set return best_header next time */
99 FifoBuffer fifo_buf; /**< buffer to store all data until headers
100 can be verified */
101 int end_padded; /**< specifies if fifo_buf's end is padded */
102 uint8_t *wrap_buf; /**< general fifo read buffer when wrapped */
103 int wrap_buf_allocated_size; /**< actual allocated size of the buffer */
104 FLACFrameInfo last_fi; /**< last decoded frame header info */
105 int last_fi_valid; /**< set if last_fi is valid */
107
108/**
109 * Reject a variable-blocksize candidate when STREAMINFO declares a fixed
110 * blocksize. This is only a sync-search check: complete container packets
111 * already have known boundaries, and their STREAMINFO can change mid-stream.
112 */
114 const FLACFrameInfo *fi)
115{
116 const uint8_t *si = avctx->extradata;
117 int size = avctx->extradata_size;
118 int min_blocksize, max_blocksize;
119
120 /* Raw/headerless FLAC has no STREAMINFO to validate against. */
121 if (!si || size < FLAC_STREAMINFO_SIZE)
122 return 1;
123
124 /* Also accept a 4-byte marker + metadata block header before STREAMINFO. */
125 if (AV_RL32(si) == MKTAG('f', 'L', 'a', 'C')) {
126 if (size < 8 + FLAC_STREAMINFO_SIZE)
127 return 1;
128 si += 8;
129 }
130
131 min_blocksize = AV_RB16(si);
132 max_blocksize = AV_RB16(si + 2);
133 /* A fixed-blocksize stream cannot contain variable-blocksize frames.
134 * Compare the strategy bit, not the blocksize: the final frame of a
135 * fixed stream may legitimately be shorter than the declared size. */
136 if (min_blocksize && max_blocksize && min_blocksize == max_blocksize &&
137 fi->is_var_size)
138 return 0;
139
140 return 1;
141}
142
143static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf,
144 FLACFrameInfo *fi)
145{
146 GetBitContext gb;
147 uint8_t subframe_type;
148
149 // header plus one byte from first subframe
151 if (ff_flac_decode_frame_header(avctx, &gb, fi, 127)) {
152 return 0;
153 }
154 // subframe zero bit
155 if (get_bits1(&gb) != 0) {
156 return 0;
157 }
158 // subframe type
159 // 000000 : SUBFRAME_CONSTANT
160 // 000001 : SUBFRAME_VERBATIM
161 // 00001x : reserved
162 // 0001xx : reserved
163 // 001xxx : if(xxx <= 4) SUBFRAME_FIXED, xxx=order ; else reserved
164 // 01xxxx : reserved
165 // 1xxxxx : SUBFRAME_LPC, xxxxx=order-1
166 subframe_type = get_bits(&gb, 6);
167 if (!(subframe_type == 0 ||
168 subframe_type == 1 ||
169 ((subframe_type >= 8) && (subframe_type <= 12)) ||
170 (subframe_type >= 32))) {
171 return 0;
172 }
173
174 return 1;
175}
176
177static size_t flac_fifo_size(const FifoBuffer *f)
178{
179 if (f->wptr <= f->rptr && !f->empty)
180 return (f->wptr - f->buffer) + (f->end - f->rptr);
181 return f->wptr - f->rptr;
182}
183
184static size_t flac_fifo_space(const FifoBuffer *f)
185{
186 return f->end - f->buffer - flac_fifo_size(f);
187}
188
189/**
190 * Non-destructive fast fifo pointer fetching
191 * Returns a pointer from the specified offset.
192 * If possible the pointer points within the fifo buffer.
193 * Otherwise (if it would cause a wrap around,) a pointer to a user-specified
194 * buffer is used.
195 * The pointer can be NULL. In any case it will be reallocated to hold the size.
196 * If the returned pointer will be used after subsequent calls to flac_fifo_read_wrap
197 * then the subsequent calls should pass in a different wrap_buf so as to not
198 * overwrite the contents of the previous wrap_buf.
199 * This function is based on av_fifo_generic_read, which is why there is a comment
200 * about a memory barrier for SMP.
201 */
202static uint8_t *flac_fifo_read_wrap(FLACParseContext *fpc, int offset, int len,
203 uint8_t **wrap_buf, int *allocated_size)
204{
205 FifoBuffer *f = &fpc->fifo_buf;
206 uint8_t *start = f->rptr + offset;
207 uint8_t *tmp_buf;
208
209 if (start >= f->end)
210 start -= f->end - f->buffer;
211 if (f->end - start >= len)
212 return start;
213
214 tmp_buf = av_fast_realloc(*wrap_buf, allocated_size, len);
215
216 if (!tmp_buf) {
218 "couldn't reallocate wrap buffer of size %d", len);
219 return NULL;
220 }
221 *wrap_buf = tmp_buf;
222 do {
223 int seg_len = FFMIN(f->end - start, len);
224 memcpy(tmp_buf, start, seg_len);
225 tmp_buf = (uint8_t*)tmp_buf + seg_len;
226// memory barrier needed for SMP here in theory
227
228 start += seg_len - (f->end - f->buffer);
229 len -= seg_len;
230 } while (len > 0);
231
232 return *wrap_buf;
233}
234
235/**
236 * Return a pointer in the fifo buffer where the offset starts at until
237 * the wrap point or end of request.
238 * len will contain the valid length of the returned buffer.
239 * A second call to flac_fifo_read (with new offset and len) should be called
240 * to get the post-wrap buf if the returned len is less than the requested.
241 **/
242static uint8_t *flac_fifo_read(FifoBuffer *f, int offset, int *len)
243{
244 uint8_t *start = f->rptr + offset;
245
246 if (start >= f->end)
247 start -= f->end - f->buffer;
248 *len = FFMIN(*len, f->end - start);
249 return start;
250}
251
252static int flac_fifo_grow(FifoBuffer *f, size_t inc)
253{
254 size_t size_old = f->end - f->buffer;
255 size_t offset_r = f->rptr - f->buffer;
256 size_t offset_w = f->wptr - f->buffer;
257 size_t size_new;
258
259 uint8_t *tmp;
260
261 if (size_old > SIZE_MAX - inc)
262 return AVERROR(EINVAL);
263 size_new = size_old + inc;
264
265 tmp = av_realloc(f->buffer, size_new);
266 if (!tmp)
267 return AVERROR(ENOMEM);
268
269 // move the data from the beginning of the ring buffer
270 // to the newly allocated space
271 if (offset_w <= offset_r && !f->empty) {
272 const size_t copy = FFMIN(inc, offset_w);
273 memcpy(tmp + size_old, tmp, copy);
274 if (copy < offset_w) {
275 memmove(tmp, tmp + copy, offset_w - copy);
276 offset_w -= copy;
277 } else
278 offset_w = size_old + copy;
279 }
280
281 f->buffer = tmp;
282 f->end = f->buffer + size_new;
283 f->rptr = f->buffer + offset_r;
284 f->wptr = f->buffer + offset_w;
285
286 return 0;
287}
288
289static int flac_fifo_write(FifoBuffer *f, const uint8_t *src, size_t size)
290{
291 uint8_t *wptr;
292
293 if (flac_fifo_space(f) < size) {
295 if (ret < 0)
296 return ret;
297 }
298
299 if (size)
300 f->empty = 0;
301
302 wptr = f->wptr;
303 do {
304 size_t len = FFMIN(f->end - wptr, size);
305 memcpy(wptr, src, len);
306 src += len;
307 wptr += len;
308 if (wptr >= f->end)
309 wptr = f->buffer;
310 size -= len;
311 } while (size > 0);
312
313 f->wptr = wptr;
314
315 return 0;
316}
317
318static void flac_fifo_drain(FifoBuffer *f, size_t size)
319{
320 size_t size_cur = flac_fifo_size(f);
321
322 av_assert0(size_cur >= size);
323 if (size_cur == size)
324 f->empty = 1;
325
326 f->rptr += size;
327 if (f->rptr >= f->end)
328 f->rptr -= f->end - f->buffer;
329}
330
331static int flac_fifo_alloc(FifoBuffer *f, size_t size)
332{
333 memset(f, 0, sizeof(*f));
334
335 f->buffer = av_realloc(NULL, size);
336 if (!f->buffer)
337 return AVERROR(ENOMEM);
338
339 f->wptr = f->buffer;
340 f->rptr = f->buffer;
341 f->end = f->buffer + size;
342
343 f->empty = 1;
344
345 return 0;
346}
347
349{
350 av_freep(&f->buffer);
351 memset(f, 0, sizeof(*f));
352}
353
355{
356 FLACFrameInfo fi;
357 uint8_t *header_buf;
358 int size = 0;
359 header_buf = flac_fifo_read_wrap(fpc, offset,
361 &fpc->wrap_buf,
363 if (frame_header_is_valid(fpc->avctx, header_buf, &fi) &&
365 FLACHeaderMarker **end_handle = &fpc->headers, *prev = NULL;
366 int i;
367
368 size = 0;
369 while (*end_handle) {
370 prev = *end_handle;
371 end_handle = &(*end_handle)->next;
372 size++;
373 }
374
375 *end_handle = av_mallocz(sizeof(**end_handle));
376 if (!*end_handle) {
378 "couldn't allocate FLACHeaderMarker\n");
379 return AVERROR(ENOMEM);
380 }
381 (*end_handle)->fi = fi;
382 (*end_handle)->offset = offset;
383 (*end_handle)->prev = prev;
384
385 for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++)
386 (*end_handle)->link_penalty[i] = FLAC_HEADER_NOT_PENALIZED_YET;
387
388 fpc->nb_headers_found++;
389 size++;
390 }
391 return size;
392}
393
394static int find_headers_search(FLACParseContext *fpc, uint8_t *buf,
395 int buf_size, int search_start)
396{
397 int size = 0, mod_offset = (buf_size - 1) % 4, i, j;
398 uint32_t x;
399
400 for (i = 0; i < mod_offset; i++) {
401 if ((AV_RB16(buf + i) & 0xFFFE) == 0xFFF8) {
402 int ret = find_headers_search_validate(fpc, search_start + i);
403 size = FFMAX(size, ret);
404 }
405 }
406
407 for (; i < buf_size - 1; i += 4) {
408 x = AV_RN32(buf + i);
409 if (((x & ~(x + 0x01010101)) & 0x80808080)) {
410 for (j = 0; j < 4; j++) {
411 if ((AV_RB16(buf + i + j) & 0xFFFE) == 0xFFF8) {
412 int ret = find_headers_search_validate(fpc, search_start + i + j);
413 size = FFMAX(size, ret);
414 }
415 }
416 }
417 }
418 return size;
419}
420
421static int find_new_headers(FLACParseContext *fpc, int search_start)
422{
423 FLACHeaderMarker *end;
424 int search_end, size = 0, read_len, temp;
425 uint8_t *buf;
426 fpc->nb_headers_found = 0;
427
428 /* Search for a new header of at most 16 bytes. */
429 search_end = flac_fifo_size(&fpc->fifo_buf) - (MAX_FRAME_HEADER_SIZE - 1);
430 read_len = search_end - search_start + 1;
431 buf = flac_fifo_read(&fpc->fifo_buf, search_start, &read_len);
432 size = find_headers_search(fpc, buf, read_len, search_start);
433 search_start += read_len - 1;
434
435 /* If fifo end was hit do the wrap around. */
436 if (search_start != search_end) {
437 uint8_t wrap[2];
438
439 wrap[0] = buf[read_len - 1];
440 /* search_start + 1 is the post-wrap offset in the fifo. */
441 read_len = search_end - (search_start + 1) + 1;
442
443 buf = flac_fifo_read(&fpc->fifo_buf, search_start + 1, &read_len);
444 wrap[1] = buf[0];
445
446 if ((AV_RB16(wrap) & 0xFFFE) == 0xFFF8) {
447 temp = find_headers_search_validate(fpc, search_start);
448 size = FFMAX(size, temp);
449 }
450 search_start++;
451
452 /* Continue to do the last half of the wrap. */
453 temp = find_headers_search(fpc, buf, read_len, search_start);
454 size = FFMAX(size, temp);
455 search_start += read_len - 1;
456 }
457
458 /* Return the size even if no new headers were found. */
459 if (!size && fpc->headers)
460 for (end = fpc->headers; end; end = end->next)
461 size++;
462 return size;
463}
464
466 FLACFrameInfo *header_fi,
467 FLACFrameInfo *child_fi,
468 int log_level_offset)
469{
470 int deduction = 0;
471 if (child_fi->samplerate != header_fi->samplerate) {
472 deduction += FLAC_HEADER_CHANGED_PENALTY;
473 av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
474 "sample rate change detected in adjacent frames\n");
475 }
476 if (child_fi->bps != header_fi->bps) {
477 deduction += FLAC_HEADER_CHANGED_PENALTY;
478 av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
479 "bits per sample change detected in adjacent frames\n");
480 }
481 if (child_fi->is_var_size != header_fi->is_var_size) {
482 /* Changing blocking strategy not allowed per the spec */
483 deduction += FLAC_HEADER_BASE_SCORE;
484 av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
485 "blocking strategy change detected in adjacent frames\n");
486 }
487 if (child_fi->channels != header_fi->channels) {
488 deduction += FLAC_HEADER_CHANGED_PENALTY;
489 av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
490 "number of channels change detected in adjacent frames\n");
491 }
492 return deduction;
493}
494
497 FLACHeaderMarker *child,
498 int log_level_offset)
499{
500 FLACFrameInfo *header_fi = &header->fi, *child_fi = &child->fi;
501 int check_crc, deduction, deduction_expected = 0, i;
502 deduction = check_header_fi_mismatch(fpc, header_fi, child_fi,
503 log_level_offset);
504 /* Check sample and frame numbers. */
505 if ((child_fi->frame_or_sample_num - header_fi->frame_or_sample_num
506 != header_fi->blocksize) &&
507 (child_fi->frame_or_sample_num
508 != header_fi->frame_or_sample_num + 1)) {
509 FLACHeaderMarker *curr;
510 int64_t expected_frame_num, expected_sample_num;
511 /* If there are frames in the middle we expect this deduction,
512 as they are probably valid and this one follows it */
513
514 expected_frame_num = expected_sample_num = header_fi->frame_or_sample_num;
515 curr = header;
516 while (curr != child) {
517 /* Ignore frames that failed all crc checks */
518 for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++) {
520 expected_frame_num++;
521 expected_sample_num += curr->fi.blocksize;
522 break;
523 }
524 }
525 curr = curr->next;
526 }
527
528 if (expected_frame_num == child_fi->frame_or_sample_num ||
529 expected_sample_num == child_fi->frame_or_sample_num)
530 deduction_expected = deduction ? 0 : 1;
531
532 deduction += FLAC_HEADER_CHANGED_PENALTY;
533 av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
534 "sample/frame number mismatch in adjacent frames\n");
535 }
536
537 if (fpc->last_fi.is_var_size == header_fi->is_var_size) {
538 if (fpc->last_fi.is_var_size &&
540 check_crc = 0;
541 } else if (!fpc->last_fi.is_var_size &&
542 fpc->last_fi.frame_or_sample_num + 1 == header_fi->frame_or_sample_num) {
543 check_crc = 0;
544 } else {
545 check_crc = !deduction && !deduction_expected;
546 }
547 } else {
548 check_crc = !deduction && !deduction_expected;
549 }
550
551 /* If we have suspicious headers, check the CRC between them */
552 if (check_crc || (deduction && !deduction_expected)) {
553 FLACHeaderMarker *curr;
554 int read_len;
555 uint8_t *buf;
556 uint32_t crc = 1;
557 int inverted_test = 0;
558
559 /* Since CRC is expensive only do it if we haven't yet.
560 This assumes a CRC penalty is greater than all other check penalties */
561 curr = header->next;
562 for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS && curr != child; i++)
563 curr = curr->next;
564
566
567 if (header->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY ||
568 header->link_penalty[i] == FLAC_HEADER_NOT_PENALIZED_YET) {
569 FLACHeaderMarker *start, *end;
570
571 /* Although overlapping chains are scored, the crc should never
572 have to be computed twice for a single byte. */
573 start = header;
574 end = child;
575 if (i > 0 &&
576 header->link_penalty[i - 1] >= FLAC_HEADER_CRC_FAIL_PENALTY) {
577 while (start->next != child)
578 start = start->next;
579 inverted_test = 1;
580 } else if (i > 0 &&
581 header->next->link_penalty[i-1] >=
583 end = header->next;
584 inverted_test = 1;
585 }
586
587 read_len = end->offset - start->offset;
588 buf = flac_fifo_read(&fpc->fifo_buf, start->offset, &read_len);
589 crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf, read_len);
590 read_len = (end->offset - start->offset) - read_len;
591
592 if (read_len) {
593 buf = flac_fifo_read(&fpc->fifo_buf, end->offset - read_len, &read_len);
594 crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), crc, buf, read_len);
595 }
596 }
597
598 if (!crc ^ !inverted_test) {
599 deduction += FLAC_HEADER_CRC_FAIL_PENALTY;
600 av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
601 "crc check failed from offset %i (frame %"PRId64") to %i (frame %"PRId64")\n",
602 header->offset, header_fi->frame_or_sample_num,
603 child->offset, child_fi->frame_or_sample_num);
604 }
605 }
606 return deduction;
607}
608
609/**
610 * Score a header.
611 *
612 * Give FLAC_HEADER_BASE_SCORE points to a frame for existing.
613 * If it has children, (subsequent frames of which the preceding CRC footer
614 * validates against this one,) then take the maximum score of the children,
615 * with a penalty of FLAC_HEADER_CHANGED_PENALTY applied for each change to
616 * bps, sample rate, channels, but not decorrelation mode, or blocksize,
617 * because it can change often.
618 **/
620{
621 FLACHeaderMarker *child;
622 int dist = 0;
623 int child_score;
624 int base_score = FLAC_HEADER_BASE_SCORE;
625 if (header->max_score != FLAC_HEADER_NOT_SCORED_YET)
626 return header->max_score;
627
628 /* Modify the base score with changes from the last output header */
629 if (fpc->last_fi_valid) {
630 /* Silence the log since this will be repeated if selected */
631 base_score -= check_header_fi_mismatch(fpc, &fpc->last_fi, &header->fi,
633 }
634
635 header->max_score = base_score;
636
637 /* Check and compute the children's scores. */
638 child = header->next;
639 for (dist = 0; dist < FLAC_MAX_SEQUENTIAL_HEADERS && child; dist++) {
640 /* Look at the child's frame header info and penalize suspicious
641 changes between the headers. */
642 if (header->link_penalty[dist] == FLAC_HEADER_NOT_PENALIZED_YET) {
643 header->link_penalty[dist] = check_header_mismatch(fpc, header,
644 child, AV_LOG_DEBUG);
645 }
646 child_score = score_header(fpc, child) - header->link_penalty[dist];
647
648 if (FLAC_HEADER_BASE_SCORE + child_score > header->max_score) {
649 /* Keep the child because the frame scoring is dynamic. */
650 header->best_child = child;
651 header->max_score = base_score + child_score;
652 }
653 child = child->next;
654 }
655
656 return header->max_score;
657}
658
660{
661 FLACHeaderMarker *curr, *last = NULL;
662 int best_score = FLAC_HEADER_NOT_SCORED_YET;
663 /* First pass to clear all old scores. */
664 for (curr = fpc->headers; curr; curr = curr->next) {
666 last = curr;
667 }
668
669 /* Score from the last header backwards, so the children of each header
670 are already scored and score_header() does not recurse. */
671 for (curr = last; curr; curr = curr->prev) {
672 if (score_header(fpc, curr) >= best_score) {
673 fpc->best_header = curr;
674 best_score = curr->max_score;
675 }
676 }
677}
678
679static int get_best_header(FLACParseContext *fpc, const uint8_t **poutbuf,
680 int *poutbuf_size)
681{
683 FLACHeaderMarker *child = header->best_child;
684 if (!child) {
685 *poutbuf_size = flac_fifo_size(&fpc->fifo_buf) - header->offset;
686 } else {
687 *poutbuf_size = child->offset - header->offset;
688
689 /* If the child has suspicious changes, log them */
690 check_header_mismatch(fpc, header, child, 0);
691 }
692
693 ff_flac_set_channel_layout(fpc->avctx, header->fi.channels);
694
695 fpc->avctx->sample_rate = header->fi.samplerate;
696 fpc->pc->duration = header->fi.blocksize;
697 *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
698 &fpc->wrap_buf,
700
701 if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
702 if (header->fi.is_var_size)
703 fpc->pc->pts = header->fi.frame_or_sample_num;
704 else if (header->best_child)
705 fpc->pc->pts = header->fi.frame_or_sample_num * header->fi.blocksize;
706 }
707
708 fpc->best_header_valid = 0;
709 fpc->last_fi_valid = 1;
710 fpc->last_fi = header->fi;
711
712 /* Return the negative overread index so the client can compute pos.
713 This should be the amount overread to the beginning of the child */
714 if (child) {
715 int64_t offset = child->offset - flac_fifo_size(&fpc->fifo_buf);
716 if (offset > -(1 << 28))
717 return offset;
718 }
719 return 0;
720}
721
723 const uint8_t **poutbuf, int *poutbuf_size,
724 const uint8_t *buf, int buf_size)
725{
726 FLACParseContext *fpc = s->priv_data;
727 FLACHeaderMarker *curr;
728 int nb_headers;
729 const uint8_t *read_end = buf;
730 const uint8_t *read_start = buf;
731
732 if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
733 FLACFrameInfo fi;
734 if (frame_header_is_valid(avctx, buf, &fi)) {
735 s->duration = fi.blocksize;
736 if (!avctx->sample_rate)
737 avctx->sample_rate = fi.samplerate;
738 if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
739 fpc->pc->pts = fi.frame_or_sample_num;
740 if (!fi.is_var_size)
741 fpc->pc->pts *= fi.blocksize;
742 }
743 }
744 *poutbuf = buf;
745 *poutbuf_size = buf_size;
746 return buf_size;
747 }
748
749 fpc->avctx = avctx;
751 return get_best_header(fpc, poutbuf, poutbuf_size);
752
753 /* If a best_header was found last call remove it with the buffer data. */
754 if (fpc->best_header && fpc->best_header->best_child) {
756 FLACHeaderMarker *best_child = fpc->best_header->best_child;
757
758 /* Remove headers in list until the end of the best_header. */
759 for (curr = fpc->headers; curr != best_child; curr = temp) {
760 if (curr != fpc->best_header) {
761 av_log(avctx, AV_LOG_DEBUG,
762 "dropping low score %i frame header from offset %i to %i\n",
763 curr->max_score, curr->offset, curr->next->offset);
764 }
765 temp = curr->next;
766 av_free(curr);
767 fpc->nb_headers_buffered--;
768 }
769 /* Release returned data from ring buffer. */
770 flac_fifo_drain(&fpc->fifo_buf, best_child->offset);
771
772 /* Fix the offset for the headers remaining to match the new buffer. */
773 for (curr = best_child->next; curr; curr = curr->next)
774 curr->offset -= best_child->offset;
775
776 best_child->offset = 0;
777 best_child->prev = NULL;
778 fpc->headers = best_child;
780 fpc->best_header = best_child;
781 return get_best_header(fpc, poutbuf, poutbuf_size);
782 }
783 fpc->best_header = NULL;
784 } else if (fpc->best_header) {
785 /* No end frame no need to delete the buffer; probably eof */
787
788 for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {
789 temp = curr->next;
790 av_free(curr);
791 fpc->nb_headers_buffered--;
792 }
793 fpc->headers = fpc->best_header->next;
794 if (fpc->headers)
795 fpc->headers->prev = NULL;
796 av_freep(&fpc->best_header);
797 fpc->nb_headers_buffered--;
798
799 /* Without a child, get_best_header() already returned everything
800 * from this header to the end of the FIFO. At EOF there can be no
801 * further frames, so any header still queued is a false sync inside
802 * that frame. Drop them and drain the FIFO, or the next flush emits
803 * part of the final frame a second time. */
804 if (fpc->end_padded) {
805 for (curr = fpc->headers; curr; curr = temp) {
806 temp = curr->next;
807 av_free(curr);
808 fpc->nb_headers_buffered--;
809 }
810 fpc->headers = NULL;
812 }
813 }
814
815 /* Find and score new headers. */
816 /* buf_size is zero when flushing, so check for this since we do */
817 /* not want to try to read more input once we have found the end. */
818 /* Also note that buf can't be NULL. */
819 while ((buf_size && read_end < buf + buf_size &&
821 || (!buf_size && !fpc->end_padded)) {
822 int start_offset, ret;
823
824 /* Pad the end once if EOF, to check the final region for headers. */
825 if (!buf_size) {
826 fpc->end_padded = 1;
827 read_end = read_start + MAX_FRAME_HEADER_SIZE;
828 } else {
829 /* The maximum read size is the upper-bound of what the parser
830 needs to have the required number of frames buffered */
831 int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;
832 read_end = read_end + FFMIN(buf + buf_size - read_end,
833 nb_desired * FLAC_AVG_FRAME_SIZE);
834 }
835
836 if (!flac_fifo_space(&fpc->fifo_buf) &&
838 fpc->nb_headers_buffered * 20) {
839 /* There is less than one valid flac header buffered for 20 headers
840 * buffered. Therefore the fifo is most likely filled with invalid
841 * data and the input is not a flac file. */
842 goto handle_error;
843 }
844
845 /* Fill the buffer. */
846 if (buf_size) {
847 ret = flac_fifo_write(&fpc->fifo_buf, read_start,
848 read_end - read_start);
849 } else {
850 int8_t pad[MAX_FRAME_HEADER_SIZE] = { 0 };
851 ret = flac_fifo_write(&fpc->fifo_buf, pad, sizeof(pad));
852 }
853 if (ret < 0) {
854 av_log(avctx, AV_LOG_ERROR, "Error buffering data\n");
855 goto handle_error;
856 }
857
858 /* Tag headers and update sequences. */
859 start_offset = flac_fifo_size(&fpc->fifo_buf) -
860 ((read_end - read_start) + (MAX_FRAME_HEADER_SIZE - 1));
861 start_offset = FFMAX(0, start_offset);
862 nb_headers = find_new_headers(fpc, start_offset);
863
864 if (nb_headers < 0) {
865 av_log(avctx, AV_LOG_ERROR,
866 "find_new_headers couldn't allocate FLAC header\n");
867 goto handle_error;
868 }
869
870 fpc->nb_headers_buffered = nb_headers;
871 /* Wait till FLAC_MIN_HEADERS to output a valid frame. */
872 if (!fpc->end_padded && fpc->nb_headers_buffered < FLAC_MIN_HEADERS) {
873 if (read_end < buf + buf_size) {
874 read_start = read_end;
875 continue;
876 } else {
877 goto handle_error;
878 }
879 }
880
881 /* If headers found, update the scores since we have longer chains. */
882 if (fpc->end_padded || fpc->nb_headers_found)
883 score_sequences(fpc);
884
885 /* restore the state pre-padding */
886 if (fpc->end_padded) {
887 int empty = flac_fifo_size(&fpc->fifo_buf) == MAX_FRAME_HEADER_SIZE;
888 int warp = fpc->fifo_buf.wptr - fpc->fifo_buf.buffer < MAX_FRAME_HEADER_SIZE;
889 /* HACK: drain the tail of the fifo */
891 if (warp) {
892 fpc->fifo_buf.wptr += fpc->fifo_buf.end -
893 fpc->fifo_buf.buffer;
894 }
895 fpc->fifo_buf.empty = empty;
896 read_start = read_end = NULL;
897 }
898 }
899
900 for (curr = fpc->headers; curr; curr = curr->next) {
901 if (!fpc->best_header || curr->max_score > fpc->best_header->max_score) {
902 fpc->best_header = curr;
903 }
904 }
905
906 if (fpc->best_header && fpc->best_header->max_score <= 0) {
907 // Only accept a bad header if there is no other option to continue
908 if (!buf_size || read_end != buf || fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
909 fpc->best_header = NULL;
910 }
911
912 if (fpc->best_header) {
913 fpc->best_header_valid = 1;
914 if (fpc->best_header->offset > 0) {
915 /* Output a junk frame. */
916 av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",
917 fpc->best_header->offset);
918
919 /* Set duration to 0. It is unknown or invalid in a junk frame. */
920 s->duration = 0;
921 *poutbuf_size = fpc->best_header->offset;
922 *poutbuf = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,
923 &fpc->wrap_buf,
925 return buf_size ? (read_end - buf) : (fpc->best_header->offset -
926 flac_fifo_size(&fpc->fifo_buf));
927 }
928 if (!buf_size)
929 return get_best_header(fpc, poutbuf, poutbuf_size);
930 }
931
932handle_error:
933 *poutbuf = NULL;
934 *poutbuf_size = 0;
935 return buf_size ? read_end - buf : 0;
936}
937
939{
940 FLACParseContext *fpc = c->priv_data;
941 int ret;
942
943 fpc->pc = c;
944 /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
945 it drains. This is allocated early to avoid slow reallocation. */
947 if (ret < 0) {
949 "couldn't allocate fifo_buf\n");
950 return AVERROR(ENOMEM);
951 }
952 return 0;
953}
954
956{
957 FLACParseContext *fpc = c->priv_data;
958 FLACHeaderMarker *curr = fpc->headers, *temp;
959
960 while (curr) {
961 temp = curr->next;
962 av_free(curr);
963 curr = temp;
964 }
965 fpc->headers = NULL;
967 av_freep(&fpc->wrap_buf);
968}
969
#define wrap(func)
Definition neontest.h:65
static int parse(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size)
Definition apv_parser.c:92
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
#define PARSER_FLAG_USE_CODEC_TS
Definition avcodec.h:2676
#define PARSER_FLAG_COMPLETE_FRAMES
Definition avcodec.h:2672
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define f(width, name)
Definition cbs_vp8.c:236
#define s(width, name)
Definition cbs_vp9.c:198
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Public header for CRC hash function implementation.
int(* init)(AVBSFContext *ctx)
Definition dts2pts.c:613
int ret
Definition ffplay.c:391
FLAC (Free Lossless Audio Codec) common stuff.
#define FLAC_STREAMINFO_SIZE
Definition flac.h:32
FLAC (Free Lossless Audio Codec) decoder/parser common functions.
static void score_sequences(FLACParseContext *fpc)
static int flac_fifo_alloc(FifoBuffer *f, size_t size)
#define FLAC_HEADER_CHANGED_PENALTY
Definition flac_parser.c:53
#define FLAC_MAX_SEQUENTIAL_HEADERS
maximum number of adjacent headers that compare CRCs against each other
Definition flac_parser.c:45
static av_cold void flac_parse_close(AVCodecParserContext *c)
static void flac_fifo_drain(FifoBuffer *f, size_t size)
static av_cold int flac_parse_init(AVCodecParserContext *c)
static int find_headers_search_validate(FLACParseContext *fpc, int offset)
static int flac_blocking_strategy_matches(const AVCodecContext *avctx, const FLACFrameInfo *fi)
Reject a variable-blocksize candidate when STREAMINFO declares a fixed blocksize.
static int score_header(FLACParseContext *fpc, FLACHeaderMarker *header)
Score a header.
#define FLAC_HEADER_NOT_SCORED_YET
Definition flac_parser.c:56
static size_t flac_fifo_size(const FifoBuffer *f)
static size_t flac_fifo_space(const FifoBuffer *f)
static int check_header_mismatch(FLACParseContext *fpc, FLACHeaderMarker *header, FLACHeaderMarker *child, int log_level_offset)
#define FLAC_HEADER_BASE_SCORE
scoring settings for score_header
Definition flac_parser.c:52
#define FLAC_AVG_FRAME_SIZE
estimate for average size of a FLAC frame
Definition flac_parser.c:49
static int flac_fifo_write(FifoBuffer *f, const uint8_t *src, size_t size)
#define MAX_FRAME_VERIFY_SIZE
Definition flac_parser.c:60
static int flac_fifo_grow(FifoBuffer *f, size_t inc)
#define FLAC_HEADER_NOT_PENALIZED_YET
Definition flac_parser.c:55
static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf, FLACFrameInfo *fi)
static int check_header_fi_mismatch(FLACParseContext *fpc, FLACFrameInfo *header_fi, FLACFrameInfo *child_fi, int log_level_offset)
static int find_headers_search(FLACParseContext *fpc, uint8_t *buf, int buf_size, int search_start)
#define MAX_FRAME_HEADER_SIZE
largest possible size of flac header
Definition flac_parser.c:59
#define FLAC_HEADER_CRC_FAIL_PENALTY
Definition flac_parser.c:54
static int get_best_header(FLACParseContext *fpc, const uint8_t **poutbuf, int *poutbuf_size)
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.
const FFCodecParser ff_flac_parser
static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx, const uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size)
#define FLAC_MIN_HEADERS
minimum number of headers buffered and checked before returning frames
Definition flac_parser.c:47
static int find_new_headers(FLACParseContext *fpc, int search_start)
static uint8_t * flac_fifo_read(FifoBuffer *f, int offset, int *len)
Return a pointer in the fifo buffer where the offset starts at until the wrap point or end of request...
static void flac_fifo_free(FifoBuffer *f)
static unsigned int get_bits1(GetBitContext *s)
Definition get_bits.h:391
static unsigned int get_bits(GetBitContext *s, int n)
Read 1-25 bits.
Definition get_bits.h:337
static int init_get_bits(GetBitContext *s, const uint8_t *buffer, int bit_size)
Initialize GetBitContext.
Definition get_bits.h:517
@ AV_CODEC_ID_FLAC
Definition codec_id.h:471
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition defs.h:40
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition crc.c:389
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:421
@ AV_CRC_16_ANSI
Definition crc.h:50
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
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:601
#define AV_RN32(p)
#define AV_RL32(p)
#define AV_RB16(p)
unsigned offset
Definition libaomenc.c:763
av_cold void CBS_FUNC close(CodedBitstreamContext **ctx_ptr)
Close a context and free all internal state.
Definition cbs.c:118
int ff_flac_decode_frame_header(void *logctx, GetBitContext *gb, FLACFrameInfo *fi, int log_level_offset)
Validate and decode a frame header.
Definition flac.c:51
void ff_flac_set_channel_layout(AVCodecContext *avctx, int channels)
Definition flac.c:173
Macro definitions for various function/variable attributes.
#define av_cold
Definition attributes.h:117
Utility Preprocessor macros.
#define FFMIN(a, b)
Definition macros.h:49
#define MKTAG(a, b, c, d)
Definition macros.h:55
#define FFMAX(a, b)
Definition macros.h:47
Memory handling functions.
#define av_realloc(p, s)
Definition ops_static.c:54
#define PARSER_CODEC_LIST(...)
static int inc(int num, int period)
Definition perlin.c:34
static const uint8_t header[24]
Definition sdr2.c:68
main external API structure.
Definition avcodec.h:443
int sample_rate
samples per second
Definition avcodec.h:1044
uint8_t * extradata
Out-of-band global headers that may be used by some codecs.
Definition avcodec.h:526
int extradata_size
Definition avcodec.h:527
int duration
Duration of the current frame.
Definition avcodec.h:2752
int blocksize
block size of the frame
Definition flac_parse.h:46
int channels
number of channels
Definition flac_parse.h:44
int samplerate
sample rate
Definition flac_parse.h:43
int is_var_size
specifies if the stream uses variable block sizes or a fixed block size; also determines the meaning ...
Definition flac_parse.h:49
int64_t frame_or_sample_num
frame number or sample number
Definition flac_parse.h:48
int bps
bits-per-sample
Definition flac_parse.h:45
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:72
int max_score
maximum score found after checking each child that has a valid CRC
Definition flac_parser.c:75
FLACFrameInfo fi
decoded frame header info
Definition flac_parser.c:77
struct FLACHeaderMarker * best_child
following frame header with which this frame has the best score with
Definition flac_parser.c:83
struct FLACHeaderMarker * prev
CRC-8 verified header that immediately precedes this one.
Definition flac_parser.c:81
struct FLACHeaderMarker * next
next CRC-8 verified header that immediately follows this one in the bytestream
Definition flac_parser.c:78
int offset
byte offset from start of FLACParseContext->buffer
Definition flac_parser.c:71
uint8_t * wrap_buf
general fifo read buffer when wrapped
FLACHeaderMarker * headers
linked-list that starts at the first CRC-8 verified header within buffer
Definition flac_parser.c:91
int last_fi_valid
set if last_fi is valid
FLACFrameInfo last_fi
last decoded frame header info
AVCodecContext * avctx
codec context pointer for logging
Definition flac_parser.c:90
FLACHeaderMarker * best_header
highest scoring header within buffer
Definition flac_parser.c:93
int nb_headers_buffered
number of headers that are buffered
Definition flac_parser.c:96
int end_padded
specifies if fifo_buf's end is padded
FifoBuffer fifo_buf
buffer to store all data until headers can be verified
Definition flac_parser.c:99
int best_header_valid
flag set when the parser returns junk; if set return best_header next time
Definition flac_parser.c:97
AVCodecParserContext * pc
parent context
Definition flac_parser.c:89
int nb_headers_found
number of headers found in the last flac_parse() call
Definition flac_parser.c:94
int wrap_buf_allocated_size
actual allocated size of the buffer
uint8_t * end
Definition flac_parser.c:64
uint8_t * buffer
Definition flac_parser.c:63
uint8_t * rptr
Definition flac_parser.c:65
uint8_t * wptr
Definition flac_parser.c:66
#define av_free(p)
#define av_mallocz(s)
#define av_freep(p)
#define av_log(a,...)
static uint8_t tmp[40]
Definition aes_ctr.c:52
static void check_crc(const AVCRC *table_new, const char *name, size_t size, size_t offset)
Definition crc.c:58
#define src
Definition vp8dsp.c:248
int size
else temp
Definition vf_mcdeint.c:275
static void copy(const float *p1, float *p2, const int length)
int len
static double c[64]