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