GCC Code Coverage Report
Directory: ../../../ffmpeg/ Exec Total Coverage
File: src/libavcodec/flac_parser.c Lines: 264 335 78.8 %
Date: 2019-11-22 03:34:36 Branches: 153 218 70.2 %

Line Branch Exec Source
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
59
typedef struct FLACHeaderMarker {
60
    int offset;       /**< byte offset from start of FLACParseContext->buffer */
61
    int link_penalty[FLAC_MAX_SEQUENTIAL_HEADERS]; /**< array of local scores
62
                           between this header and the one at a distance equal
63
                           array position                                     */
64
    int max_score;    /**< maximum score found after checking each child that
65
                           has a valid CRC                                    */
66
    FLACFrameInfo fi; /**< decoded frame header info                          */
67
    struct FLACHeaderMarker *next;       /**< next CRC-8 verified header that
68
                                              immediately follows this one in
69
                                              the bytestream                  */
70
    struct FLACHeaderMarker *best_child; /**< following frame header with
71
                                              which this frame has the best
72
                                              score with                      */
73
} FLACHeaderMarker;
74
75
typedef struct FLACParseContext {
76
    AVCodecParserContext *pc;      /**< parent context                        */
77
    AVCodecContext *avctx;         /**< codec context pointer for logging     */
78
    FLACHeaderMarker *headers;     /**< linked-list that starts at the first
79
                                        CRC-8 verified header within buffer   */
80
    FLACHeaderMarker *best_header; /**< highest scoring header within buffer  */
81
    int nb_headers_found;          /**< number of headers found in the last
82
                                        flac_parse() call                     */
83
    int nb_headers_buffered;       /**< number of headers that are buffered   */
84
    int best_header_valid;         /**< flag set when the parser returns junk;
85
                                        if set return best_header next time   */
86
    AVFifoBuffer *fifo_buf;        /**< buffer to store all data until headers
87
                                        can be verified                       */
88
    int end_padded;                /**< specifies if fifo_buf's end is padded */
89
    uint8_t *wrap_buf;             /**< general fifo read buffer when wrapped */
90
    int wrap_buf_allocated_size;   /**< actual allocated size of the buffer   */
91
    FLACFrameInfo last_fi;         /**< last decoded frame header info        */
92
    int last_fi_valid;             /**< set if last_fi is valid               */
93
} FLACParseContext;
94
95
4624
static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf,
96
                                 FLACFrameInfo *fi)
97
{
98
    GetBitContext gb;
99
4624
    init_get_bits(&gb, buf, MAX_FRAME_HEADER_SIZE * 8);
100
4624
    return !ff_flac_decode_frame_header(avctx, &gb, fi, 127);
101
}
102
103
/**
104
 * Non-destructive fast fifo pointer fetching
105
 * Returns a pointer from the specified offset.
106
 * If possible the pointer points within the fifo buffer.
107
 * Otherwise (if it would cause a wrap around,) a pointer to a user-specified
108
 * buffer is used.
109
 * The pointer can be NULL.  In any case it will be reallocated to hold the size.
110
 * If the returned pointer will be used after subsequent calls to flac_fifo_read_wrap
111
 * then the subsequent calls should pass in a different wrap_buf so as to not
112
 * overwrite the contents of the previous wrap_buf.
113
 * This function is based on av_fifo_generic_read, which is why there is a comment
114
 * about a memory barrier for SMP.
115
 */
116
7302
static uint8_t *flac_fifo_read_wrap(FLACParseContext *fpc, int offset, int len,
117
                                    uint8_t **wrap_buf, int *allocated_size)
118
{
119
7302
    AVFifoBuffer *f   = fpc->fifo_buf;
120
7302
    uint8_t *start    = f->rptr + offset;
121
    uint8_t *tmp_buf;
122
123
7302
    if (start >= f->end)
124
1343
        start -= f->end - f->buffer;
125
7302
    if (f->end - start >= len)
126
7179
        return start;
127
128
123
    tmp_buf = av_fast_realloc(*wrap_buf, allocated_size, len);
129
130
123
    if (!tmp_buf) {
131
        av_log(fpc->avctx, AV_LOG_ERROR,
132
               "couldn't reallocate wrap buffer of size %d", len);
133
        return NULL;
134
    }
135
123
    *wrap_buf = tmp_buf;
136
    do {
137
246
        int seg_len = FFMIN(f->end - start, len);
138
246
        memcpy(tmp_buf, start, seg_len);
139
246
        tmp_buf = (uint8_t*)tmp_buf + seg_len;
140
// memory barrier needed for SMP here in theory
141
142
246
        start += seg_len - (f->end - f->buffer);
143
246
        len -= seg_len;
144
246
    } while (len > 0);
145
146
123
    return *wrap_buf;
147
}
148
149
/**
150
 * Return a pointer in the fifo buffer where the offset starts at until
151
 * the wrap point or end of request.
152
 * len will contain the valid length of the returned buffer.
153
 * A second call to flac_fifo_read (with new offset and len) should be called
154
 * to get the post-wrap buf if the returned len is less than the requested.
155
 **/
156
29642
static uint8_t *flac_fifo_read(FLACParseContext *fpc, int offset, int *len)
157
{
158
29642
    AVFifoBuffer *f   = fpc->fifo_buf;
159
29642
    uint8_t *start    = f->rptr + offset;
160
161
29642
    if (start >= f->end)
162
13455
        start -= f->end - f->buffer;
163
29642
    *len = FFMIN(*len, f->end - start);
164
29642
    return start;
165
}
166
167
4586
static int find_headers_search_validate(FLACParseContext *fpc, int offset)
168
{
169
    FLACFrameInfo fi;
170
    uint8_t *header_buf;
171
4586
    int size = 0;
172
4586
    header_buf = flac_fifo_read_wrap(fpc, offset,
173
                                     MAX_FRAME_HEADER_SIZE,
174
                                     &fpc->wrap_buf,
175
                                     &fpc->wrap_buf_allocated_size);
176
4586
    if (frame_header_is_valid(fpc->avctx, header_buf, &fi)) {
177
3835
        FLACHeaderMarker **end_handle = &fpc->headers;
178
        int i;
179
180
3835
        size = 0;
181
31256
        while (*end_handle) {
182
27421
            end_handle = &(*end_handle)->next;
183
27421
            size++;
184
        }
185
186
3835
        *end_handle = av_mallocz(sizeof(**end_handle));
187
3835
        if (!*end_handle) {
188
            av_log(fpc->avctx, AV_LOG_ERROR,
189
                   "couldn't allocate FLACHeaderMarker\n");
190
            return AVERROR(ENOMEM);
191
        }
192
3835
        (*end_handle)->fi     = fi;
193
3835
        (*end_handle)->offset = offset;
194
195
19175
        for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++)
196
15340
            (*end_handle)->link_penalty[i] = FLAC_HEADER_NOT_PENALIZED_YET;
197
198
3835
        fpc->nb_headers_found++;
199
3835
        size++;
200
    }
201
4586
    return size;
202
}
203
204
29642
static int find_headers_search(FLACParseContext *fpc, uint8_t *buf,
205
                               int buf_size, int search_start)
206
{
207
29642
    int size = 0, mod_offset = (buf_size - 1) % 4, i, j;
208
    uint32_t x;
209
210
30290
    for (i = 0; i < mod_offset; i++) {
211
648
        if ((AV_RB16(buf + i) & 0xFFFE) == 0xFFF8)
212
60
            size = find_headers_search_validate(fpc, search_start + i);
213
    }
214
215
7564715
    for (; i < buf_size - 1; i += 4) {
216
7535073
        x = AV_RN32(buf + i);
217
7535073
        if (((x & ~(x + 0x01010101)) & 0x80808080)) {
218
525050
            for (j = 0; j < 4; j++) {
219
420040
                if ((AV_RB16(buf + i + j) & 0xFFFE) == 0xFFF8)
220
4526
                    size = find_headers_search_validate(fpc, search_start + i + j);
221
            }
222
        }
223
    }
224
29642
    return size;
225
}
226
227
29504
static int find_new_headers(FLACParseContext *fpc, int search_start)
228
{
229
    FLACHeaderMarker *end;
230
29504
    int search_end, size = 0, read_len, temp;
231
    uint8_t *buf;
232
29504
    fpc->nb_headers_found = 0;
233
234
    /* Search for a new header of at most 16 bytes. */
235
29504
    search_end = av_fifo_size(fpc->fifo_buf) - (MAX_FRAME_HEADER_SIZE - 1);
236
29504
    read_len   = search_end - search_start + 1;
237
29504
    buf        = flac_fifo_read(fpc, search_start, &read_len);
238
29504
    size       = find_headers_search(fpc, buf, read_len, search_start);
239
29504
    search_start += read_len - 1;
240
241
    /* If fifo end was hit do the wrap around. */
242
29504
    if (search_start != search_end) {
243
        uint8_t wrap[2];
244
245
138
        wrap[0]  = buf[read_len - 1];
246
        /* search_start + 1 is the post-wrap offset in the fifo. */
247
138
        read_len = search_end - (search_start + 1) + 1;
248
249
138
        buf      = flac_fifo_read(fpc, search_start + 1, &read_len);
250
138
        wrap[1]  = buf[0];
251
252
138
        if ((AV_RB16(wrap) & 0xFFFE) == 0xFFF8) {
253
            temp = find_headers_search_validate(fpc, search_start);
254
            size = FFMAX(size, temp);
255
        }
256
138
        search_start++;
257
258
        /* Continue to do the last half of the wrap. */
259
138
        temp     = find_headers_search(fpc, buf, read_len, search_start);
260
138
        size     = FFMAX(size, temp);
261
138
        search_start += read_len - 1;
262
    }
263
264
    /* Return the size even if no new headers were found. */
265

29504
    if (!size && fpc->headers)
266
251936
        for (end = fpc->headers; end; end = end->next)
267
225902
            size++;
268
29504
    return size;
269
}
270
271
38694
static int check_header_fi_mismatch(FLACParseContext  *fpc,
272
                                    FLACFrameInfo     *header_fi,
273
                                    FLACFrameInfo     *child_fi,
274
                                    int                log_level_offset)
275
{
276
38694
    int deduction = 0;
277
38694
    if (child_fi->samplerate != header_fi->samplerate) {
278
        deduction += FLAC_HEADER_CHANGED_PENALTY;
279
        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
280
               "sample rate change detected in adjacent frames\n");
281
    }
282
38694
    if (child_fi->bps != header_fi->bps) {
283
        deduction += FLAC_HEADER_CHANGED_PENALTY;
284
        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
285
               "bits per sample change detected in adjacent frames\n");
286
    }
287
38694
    if (child_fi->is_var_size != header_fi->is_var_size) {
288
        /* Changing blocking strategy not allowed per the spec */
289
        deduction += FLAC_HEADER_BASE_SCORE;
290
        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
291
               "blocking strategy change detected in adjacent frames\n");
292
    }
293
38694
    if (child_fi->channels != header_fi->channels) {
294
        deduction += FLAC_HEADER_CHANGED_PENALTY;
295
        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
296
               "number of channels change detected in adjacent frames\n");
297
    }
298
38694
    return deduction;
299
}
300
301
16307
static int check_header_mismatch(FLACParseContext  *fpc,
302
                                 FLACHeaderMarker  *header,
303
                                 FLACHeaderMarker  *child,
304
                                 int                log_level_offset)
305
{
306
16307
    FLACFrameInfo  *header_fi = &header->fi, *child_fi = &child->fi;
307
16307
    int deduction, deduction_expected = 0, i;
308
16307
    deduction = check_header_fi_mismatch(fpc, header_fi, child_fi,
309
                                         log_level_offset);
310
    /* Check sample and frame numbers. */
311
16307
    if ((child_fi->frame_or_sample_num - header_fi->frame_or_sample_num
312
16307
         != header_fi->blocksize) &&
313
16307
        (child_fi->frame_or_sample_num
314
16307
         != header_fi->frame_or_sample_num + 1)) {
315
        FLACHeaderMarker *curr;
316
        int64_t expected_frame_num, expected_sample_num;
317
        /* If there are frames in the middle we expect this deduction,
318
           as they are probably valid and this one follows it */
319
320
10059
        expected_frame_num = expected_sample_num = header_fi->frame_or_sample_num;
321
10059
        curr = header;
322
39924
        while (curr != child) {
323
            /* Ignore frames that failed all crc checks */
324
29865
            for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++) {
325
29865
                if (curr->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY) {
326
29865
                    expected_frame_num++;
327
29865
                    expected_sample_num += curr->fi.blocksize;
328
29865
                    break;
329
                }
330
            }
331
29865
            curr = curr->next;
332
        }
333
334
10059
        if (expected_frame_num  == child_fi->frame_or_sample_num ||
335
            expected_sample_num == child_fi->frame_or_sample_num)
336
10059
            deduction_expected = deduction ? 0 : 1;
337
338
10059
        deduction += FLAC_HEADER_CHANGED_PENALTY;
339
10059
        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
340
                   "sample/frame number mismatch in adjacent frames\n");
341
    }
342
343
    /* If we have suspicious headers, check the CRC between them */
344

16307
    if (deduction && !deduction_expected) {
345
        FLACHeaderMarker *curr;
346
        int read_len;
347
        uint8_t *buf;
348
        uint32_t crc = 1;
349
        int inverted_test = 0;
350
351
        /* Since CRC is expensive only do it if we haven't yet.
352
           This assumes a CRC penalty is greater than all other check penalties */
353
        curr = header->next;
354
        for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS && curr != child; i++)
355
            curr = curr->next;
356
357
        if (header->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY ||
358
            header->link_penalty[i] == FLAC_HEADER_NOT_PENALIZED_YET) {
359
            FLACHeaderMarker *start, *end;
360
361
            /* Although overlapping chains are scored, the crc should never
362
               have to be computed twice for a single byte. */
363
            start = header;
364
            end   = child;
365
            if (i > 0 &&
366
                header->link_penalty[i - 1] >= FLAC_HEADER_CRC_FAIL_PENALTY) {
367
                while (start->next != child)
368
                    start = start->next;
369
                inverted_test = 1;
370
            } else if (i > 0 &&
371
                       header->next->link_penalty[i-1] >=
372
                       FLAC_HEADER_CRC_FAIL_PENALTY ) {
373
                end = header->next;
374
                inverted_test = 1;
375
            }
376
377
            read_len = end->offset - start->offset;
378
            buf      = flac_fifo_read(fpc, start->offset, &read_len);
379
            crc      = av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf, read_len);
380
            read_len = (end->offset - start->offset) - read_len;
381
382
            if (read_len) {
383
                buf = flac_fifo_read(fpc, end->offset - read_len, &read_len);
384
                crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), crc, buf, read_len);
385
            }
386
        }
387
388
        if (!crc ^ !inverted_test) {
389
            deduction += FLAC_HEADER_CRC_FAIL_PENALTY;
390
            av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
391
                   "crc check failed from offset %i (frame %"PRId64") to %i (frame %"PRId64")\n",
392
                   header->offset, header_fi->frame_or_sample_num,
393
                   child->offset, child_fi->frame_or_sample_num);
394
        }
395
    }
396
16307
    return deduction;
397
}
398
399
/**
400
 * Score a header.
401
 *
402
 * Give FLAC_HEADER_BASE_SCORE points to a frame for existing.
403
 * If it has children, (subsequent frames of which the preceding CRC footer
404
 * validates against this one,) then take the maximum score of the children,
405
 * with a penalty of FLAC_HEADER_CHANGED_PENALTY applied for each change to
406
 * bps, sample rate, channels, but not decorrelation mode, or blocksize,
407
 * because it can change often.
408
 **/
409
95858
static int score_header(FLACParseContext *fpc, FLACHeaderMarker *header)
410
{
411
    FLACHeaderMarker *child;
412
95858
    int dist = 0;
413
    int child_score;
414
95858
    int base_score = FLAC_HEADER_BASE_SCORE;
415
95858
    if (header->max_score != FLAC_HEADER_NOT_SCORED_YET)
416
71890
        return header->max_score;
417
418
    /* Modify the base score with changes from the last output header */
419
23968
    if (fpc->last_fi_valid) {
420
        /* Silence the log since this will be repeated if selected */
421
22387
        base_score -= check_header_fi_mismatch(fpc, &fpc->last_fi, &header->fi,
422
                                               AV_LOG_DEBUG);
423
    }
424
425
23968
    header->max_score = base_score;
426
427
    /* Check and compute the children's scores. */
428
23968
    child = header->next;
429

95858
    for (dist = 0; dist < FLAC_MAX_SEQUENTIAL_HEADERS && child; dist++) {
430
        /* Look at the child's frame header info and penalize suspicious
431
           changes between the headers. */
432
71890
        if (header->link_penalty[dist] == FLAC_HEADER_NOT_PENALIZED_YET) {
433
13728
            header->link_penalty[dist] = check_header_mismatch(fpc, header,
434
                                                               child, AV_LOG_DEBUG);
435
        }
436
71890
        child_score = score_header(fpc, child) - header->link_penalty[dist];
437
438
71890
        if (FLAC_HEADER_BASE_SCORE + child_score > header->max_score) {
439
            /* Keep the child because the frame scoring is dynamic. */
440
21565
            header->best_child = child;
441
21565
            header->max_score  = base_score + child_score;
442
        }
443
71890
        child = child->next;
444
    }
445
446
23968
    return header->max_score;
447
}
448
449
2403
static void score_sequences(FLACParseContext *fpc)
450
{
451
    FLACHeaderMarker *curr;
452
2403
    int best_score = 0;//FLAC_HEADER_NOT_SCORED_YET;
453
    /* First pass to clear all old scores. */
454
26371
    for (curr = fpc->headers; curr; curr = curr->next)
455
23968
        curr->max_score = FLAC_HEADER_NOT_SCORED_YET;
456
457
    /* Do a second pass to score them all. */
458
26371
    for (curr = fpc->headers; curr; curr = curr->next) {
459
23968
        if (score_header(fpc, curr) > best_score) {
460
2403
            fpc->best_header = curr;
461
2403
            best_score       = curr->max_score;
462
        }
463
    }
464
2403
}
465
466
2610
static int get_best_header(FLACParseContext *fpc, const uint8_t **poutbuf,
467
                           int *poutbuf_size)
468
{
469
2610
    FLACHeaderMarker *header = fpc->best_header;
470
2610
    FLACHeaderMarker *child  = header->best_child;
471
2610
    if (!child) {
472
31
        *poutbuf_size = av_fifo_size(fpc->fifo_buf) - header->offset;
473
    } else {
474
2579
        *poutbuf_size = child->offset - header->offset;
475
476
        /* If the child has suspicious changes, log them */
477
2579
        check_header_mismatch(fpc, header, child, 0);
478
    }
479
480
2610
    if (header->fi.channels != fpc->avctx->channels ||
481
2610
        !fpc->avctx->channel_layout) {
482
        fpc->avctx->channels = header->fi.channels;
483
        ff_flac_set_channel_layout(fpc->avctx);
484
    }
485
2610
    fpc->avctx->sample_rate = header->fi.samplerate;
486
2610
    fpc->pc->duration       = header->fi.blocksize;
487
2610
    *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
488
                                        &fpc->wrap_buf,
489
                                        &fpc->wrap_buf_allocated_size);
490
491
492
2610
    if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
493
2610
        if (header->fi.is_var_size)
494
          fpc->pc->pts = header->fi.frame_or_sample_num;
495
2610
        else if (header->best_child)
496
2579
          fpc->pc->pts = header->fi.frame_or_sample_num * header->fi.blocksize;
497
    }
498
499
2610
    fpc->best_header_valid = 0;
500
2610
    fpc->last_fi_valid = 1;
501
2610
    fpc->last_fi = header->fi;
502
503
    /* Return the negative overread index so the client can compute pos.
504
       This should be the amount overread to the beginning of the child */
505
2610
    if (child)
506
2579
        return child->offset - av_fifo_size(fpc->fifo_buf);
507
31
    return 0;
508
}
509
510
32158
static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,
511
                      const uint8_t **poutbuf, int *poutbuf_size,
512
                      const uint8_t *buf, int buf_size)
513
{
514
32158
    FLACParseContext *fpc = s->priv_data;
515
    FLACHeaderMarker *curr;
516
    int nb_headers;
517
32158
    const uint8_t *read_end   = buf;
518
32158
    const uint8_t *read_start = buf;
519
520
32158
    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
521
        FLACFrameInfo fi;
522
38
        if (frame_header_is_valid(avctx, buf, &fi)) {
523
37
            s->duration = fi.blocksize;
524
37
            if (!avctx->sample_rate)
525
                avctx->sample_rate = fi.samplerate;
526
37
            if (fpc->pc->flags & PARSER_FLAG_USE_CODEC_TS) {
527
                fpc->pc->pts = fi.frame_or_sample_num;
528
                if (!fi.is_var_size)
529
                  fpc->pc->pts *= fi.blocksize;
530
            }
531
        }
532
38
        *poutbuf      = buf;
533
38
        *poutbuf_size = buf_size;
534
38
        return buf_size;
535
    }
536
537
32120
    fpc->avctx = avctx;
538
32120
    if (fpc->best_header_valid)
539
2363
        return get_best_header(fpc, poutbuf, poutbuf_size);
540
541
    /* If a best_header was found last call remove it with the buffer data. */
542

29757
    if (fpc->best_header && fpc->best_header->best_child) {
543
        FLACHeaderMarker *temp;
544
2471
        FLACHeaderMarker *best_child = fpc->best_header->best_child;
545
546
        /* Remove headers in list until the end of the best_header. */
547
4942
        for (curr = fpc->headers; curr != best_child; curr = temp) {
548
2471
            if (curr != fpc->best_header) {
549
                av_log(avctx, AV_LOG_DEBUG,
550
                       "dropping low score %i frame header from offset %i to %i\n",
551
                       curr->max_score, curr->offset, curr->next->offset);
552
            }
553
2471
            temp = curr->next;
554
2471
            av_free(curr);
555
2471
            fpc->nb_headers_buffered--;
556
        }
557
        /* Release returned data from ring buffer. */
558
2471
        av_fifo_drain(fpc->fifo_buf, best_child->offset);
559
560
        /* Fix the offset for the headers remaining to match the new buffer. */
561
21396
        for (curr = best_child->next; curr; curr = curr->next)
562
18925
            curr->offset -= best_child->offset;
563
564
2471
        best_child->offset = 0;
565
2471
        fpc->headers       = best_child;
566
2471
        if (fpc->nb_headers_buffered >= FLAC_MIN_HEADERS) {
567
29
            fpc->best_header = best_child;
568
29
            return get_best_header(fpc, poutbuf, poutbuf_size);
569
        }
570
2442
        fpc->best_header   = NULL;
571
27286
    } else if (fpc->best_header) {
572
        /* No end frame no need to delete the buffer; probably eof */
573
        FLACHeaderMarker *temp;
574
575
31
        for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {
576
            temp = curr->next;
577
            av_free(curr);
578
            fpc->nb_headers_buffered--;
579
        }
580
31
        fpc->headers = fpc->best_header->next;
581
31
        av_freep(&fpc->best_header);
582
31
        fpc->nb_headers_buffered--;
583
    }
584
585
    /* Find and score new headers.                                     */
586
    /* buf_size is zero when flushing, so check for this since we do   */
587
    /* not want to try to read more input once we have found the end.  */
588
    /* Also note that buf can't be NULL.                               */
589

32131
    while ((buf_size && read_end < buf + buf_size &&
590
29470
            fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
591

2661
           || (!buf_size && !fpc->end_padded)) {
592
        int start_offset;
593
594
        /* Pad the end once if EOF, to check the final region for headers. */
595
29504
        if (!buf_size) {
596
34
            fpc->end_padded = 1;
597
34
            read_end = read_start + MAX_FRAME_HEADER_SIZE;
598
        } else {
599
            /* The maximum read size is the upper-bound of what the parser
600
               needs to have the required number of frames buffered */
601
29470
            int nb_desired = FLAC_MIN_HEADERS - fpc->nb_headers_buffered + 1;
602
29470
            read_end       = read_end + FFMIN(buf + buf_size - read_end,
603
                                              nb_desired * FLAC_AVG_FRAME_SIZE);
604
        }
605
606
29504
        if (!av_fifo_space(fpc->fifo_buf) &&
607
            av_fifo_size(fpc->fifo_buf) / FLAC_AVG_FRAME_SIZE >
608
            fpc->nb_headers_buffered * 20) {
609
            /* There is less than one valid flac header buffered for 20 headers
610
             * buffered. Therefore the fifo is most likely filled with invalid
611
             * data and the input is not a flac file. */
612
            goto handle_error;
613
        }
614
615
        /* Fill the buffer. */
616
29504
        if (   av_fifo_space(fpc->fifo_buf) < read_end - read_start
617
23
            && av_fifo_realloc2(fpc->fifo_buf, (read_end - read_start) + 2*av_fifo_size(fpc->fifo_buf)) < 0) {
618
            av_log(avctx, AV_LOG_ERROR,
619
                   "couldn't reallocate buffer of size %"PTRDIFF_SPECIFIER"\n",
620
                   (read_end - read_start) + av_fifo_size(fpc->fifo_buf));
621
            goto handle_error;
622
        }
623
624
29504
        if (buf_size) {
625
29470
            av_fifo_generic_write(fpc->fifo_buf, (void*) read_start,
626
29470
                                  read_end - read_start, NULL);
627
        } else {
628
34
            int8_t pad[MAX_FRAME_HEADER_SIZE] = { 0 };
629
34
            av_fifo_generic_write(fpc->fifo_buf, pad, sizeof(pad), NULL);
630
        }
631
632
        /* Tag headers and update sequences. */
633
29504
        start_offset = av_fifo_size(fpc->fifo_buf) -
634
29504
                       ((read_end - read_start) + (MAX_FRAME_HEADER_SIZE - 1));
635
29504
        start_offset = FFMAX(0, start_offset);
636
29504
        nb_headers   = find_new_headers(fpc, start_offset);
637
638
29504
        if (nb_headers < 0) {
639
            av_log(avctx, AV_LOG_ERROR,
640
                   "find_new_headers couldn't allocate FLAC header\n");
641
            goto handle_error;
642
        }
643
644
29504
        fpc->nb_headers_buffered = nb_headers;
645
        /* Wait till FLAC_MIN_HEADERS to output a valid frame. */
646

29504
        if (!fpc->end_padded && fpc->nb_headers_buffered < FLAC_MIN_HEADERS) {
647
27101
            if (read_end < buf + buf_size) {
648
                read_start = read_end;
649
                continue;
650
            } else {
651
27101
                goto handle_error;
652
            }
653
        }
654
655
        /* If headers found, update the scores since we have longer chains. */
656

2403
        if (fpc->end_padded || fpc->nb_headers_found)
657
2403
            score_sequences(fpc);
658
659
        /* restore the state pre-padding */
660
2403
        if (fpc->end_padded) {
661
34
            int warp = fpc->fifo_buf->wptr - fpc->fifo_buf->buffer < MAX_FRAME_HEADER_SIZE;
662
            /* HACK: drain the tail of the fifo */
663
34
            fpc->fifo_buf->wptr -= MAX_FRAME_HEADER_SIZE;
664
34
            fpc->fifo_buf->wndx -= MAX_FRAME_HEADER_SIZE;
665
34
            if (warp) {
666
                fpc->fifo_buf->wptr += fpc->fifo_buf->end -
667
                    fpc->fifo_buf->buffer;
668
            }
669
34
            read_start = read_end = NULL;
670
        }
671
    }
672
673
27460
    for (curr = fpc->headers; curr; curr = curr->next) {
674

24833
        if (!fpc->best_header || curr->max_score > fpc->best_header->max_score) {
675
193
            fpc->best_header = curr;
676
        }
677
    }
678
679

2627
    if (fpc->best_header && fpc->best_header->max_score <= 0) {
680
        // Only accept a bad header if there is no other option to continue
681
        if (!buf_size || read_end != buf || fpc->nb_headers_buffered < FLAC_MIN_HEADERS)
682
            fpc->best_header = NULL;
683
    }
684
685
2627
    if (fpc->best_header) {
686
2596
        fpc->best_header_valid = 1;
687
2596
        if (fpc->best_header->offset > 0) {
688
            /* Output a junk frame. */
689
106
            av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",
690
106
                   fpc->best_header->offset);
691
692
            /* Set duration to 0. It is unknown or invalid in a junk frame. */
693
106
            s->duration   = 0;
694
106
            *poutbuf_size = fpc->best_header->offset;
695
106
            *poutbuf      = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,
696
                                                &fpc->wrap_buf,
697
                                                &fpc->wrap_buf_allocated_size);
698
115
            return buf_size ? (read_end - buf) : (fpc->best_header->offset -
699
9
                                                  av_fifo_size(fpc->fifo_buf));
700
        }
701
2490
        if (!buf_size)
702
218
            return get_best_header(fpc, poutbuf, poutbuf_size);
703
    }
704
705
2303
handle_error:
706
29404
    *poutbuf      = NULL;
707
29404
    *poutbuf_size = 0;
708
29404
    return buf_size ? read_end - buf : 0;
709
}
710
711
194
static av_cold int flac_parse_init(AVCodecParserContext *c)
712
{
713
194
    FLACParseContext *fpc = c->priv_data;
714
194
    fpc->pc = c;
715
    /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
716
       it drains.  This is allocated early to avoid slow reallocation. */
717
194
    fpc->fifo_buf = av_fifo_alloc_array(FLAC_MIN_HEADERS + 3, FLAC_AVG_FRAME_SIZE);
718
194
    if (!fpc->fifo_buf) {
719
        av_log(fpc->avctx, AV_LOG_ERROR,
720
                "couldn't allocate fifo_buf\n");
721
        return AVERROR(ENOMEM);
722
    }
723
194
    return 0;
724
}
725
726
194
static void flac_parse_close(AVCodecParserContext *c)
727
{
728
194
    FLACParseContext *fpc = c->priv_data;
729
194
    FLACHeaderMarker *curr = fpc->headers, *temp;
730
731
1527
    while (curr) {
732
1333
        temp = curr->next;
733
1333
        av_free(curr);
734
1333
        curr = temp;
735
    }
736
194
    fpc->headers = NULL;
737
194
    av_fifo_freep(&fpc->fifo_buf);
738
194
    av_freep(&fpc->wrap_buf);
739
194
}
740
741
AVCodecParser ff_flac_parser = {
742
    .codec_ids      = { AV_CODEC_ID_FLAC },
743
    .priv_data_size = sizeof(FLACParseContext),
744
    .parser_init    = flac_parse_init,
745
    .parser_parse   = flac_parse,
746
    .parser_close   = flac_parse_close,
747
};