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