Browse code

Add a FLAC parser. Seek test reference updated because FLAC seeking now works properly. Fixes roundup issue 1150.

Patch by Michael Chinen [mchinen at gmail]

Originally committed as revision 25914 to svn://svn.ffmpeg.org/ffmpeg/trunk

Michael Chinen authored on 2010/12/07 23:50:50
Showing 7 changed files
... ...
@@ -63,6 +63,7 @@ version <next>:
63 63
 - frei0r source added
64 64
 - hqdn3d filter added
65 65
 - RTP depacketization of QCELP
66
+- FLAC parser added
66 67
 
67 68
 
68 69
 version 0.6:
... ...
@@ -1351,6 +1351,7 @@ asf_stream_muxer_select="asf_muxer"
1351 1351
 avisynth_demuxer_deps="avisynth"
1352 1352
 dirac_demuxer_deps="dirac_parser"
1353 1353
 eac3_demuxer_select="ac3_parser"
1354
+flac_demuxer_deps="flac_parser"
1354 1355
 ipod_muxer_select="mov_muxer"
1355 1356
 libnut_demuxer_deps="libnut"
1356 1357
 libnut_muxer_deps="libnut"
... ...
@@ -570,6 +570,7 @@ OBJS-$(CONFIG_DIRAC_PARSER)            += dirac_parser.o
570 570
 OBJS-$(CONFIG_DNXHD_PARSER)            += dnxhd_parser.o
571 571
 OBJS-$(CONFIG_DVBSUB_PARSER)           += dvbsub_parser.o
572 572
 OBJS-$(CONFIG_DVDSUB_PARSER)           += dvdsub_parser.o
573
+OBJS-$(CONFIG_FLAC_PARSER)             += flac_parser.o flacdata.o flac.o
573 574
 OBJS-$(CONFIG_H261_PARSER)             += h261_parser.o
574 575
 OBJS-$(CONFIG_H263_PARSER)             += h263_parser.o
575 576
 OBJS-$(CONFIG_H264_PARSER)             += h264_parser.o h264.o            \
... ...
@@ -376,6 +376,7 @@ void avcodec_register_all(void)
376 376
     REGISTER_PARSER  (DNXHD, dnxhd);
377 377
     REGISTER_PARSER  (DVBSUB, dvbsub);
378 378
     REGISTER_PARSER  (DVDSUB, dvdsub);
379
+    REGISTER_PARSER  (FLAC, flac);
379 380
     REGISTER_PARSER  (H261, h261);
380 381
     REGISTER_PARSER  (H263, h263);
381 382
     REGISTER_PARSER  (H264, h264);
... ...
@@ -32,7 +32,7 @@
32 32
 #include "libavutil/cpu.h"
33 33
 
34 34
 #define LIBAVCODEC_VERSION_MAJOR 52
35
-#define LIBAVCODEC_VERSION_MINOR 98
35
+#define LIBAVCODEC_VERSION_MINOR 99
36 36
 #define LIBAVCODEC_VERSION_MICRO  0
37 37
 
38 38
 #define LIBAVCODEC_VERSION_INT  AV_VERSION_INT(LIBAVCODEC_VERSION_MAJOR, \
39 39
new file mode 100644
... ...
@@ -0,0 +1,648 @@
0
+/*
1
+ * FLAC parser
2
+ * Copyright (c) 2010 Michael Chinen
3
+ *
4
+ * This file is part of FFmpeg.
5
+ *
6
+ * FFmpeg is free software; you can redistribute it and/or
7
+ * modify it under the terms of the GNU Lesser General Public
8
+ * License as published by the Free Software Foundation; either
9
+ * version 2.1 of the License, or (at your option) any later version.
10
+ *
11
+ * FFmpeg is distributed in the hope that it will be useful,
12
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
+ * Lesser General Public License for more details.
15
+ *
16
+ * You should have received a copy of the GNU Lesser General Public
17
+ * License along with FFmpeg; if not, write to the Free Software
18
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
+ */
20
+
21
+/**
22
+ * @file
23
+ * FLAC parser
24
+ *
25
+ * The FLAC parser buffers input until FLAC_MIN_HEADERS has been found.
26
+ * Each time it finds and verifies a CRC-8 header it sees which of the
27
+ * FLAC_MAX_SEQUENTIAL_HEADERS that came before it have a valid CRC-16 footer
28
+ * that ends at the newly found header.
29
+ * Headers are scored by FLAC_HEADER_BASE_SCORE plus the max of it's crc-verified
30
+ * children, penalized by changes in sample rate, frame number, etc.
31
+ * The parser returns the frame with the highest score.
32
+ **/
33
+
34
+#include "libavutil/crc.h"
35
+#include "libavutil/fifo.h"
36
+#include "bytestream.h"
37
+#include "parser.h"
38
+#include "flac.h"
39
+
40
+/** maximum number of adjacent headers that compare CRCs against each other   */
41
+#define FLAC_MAX_SEQUENTIAL_HEADERS 3
42
+/** minimum number of headers buffered and checked before returning frames    */
43
+#define FLAC_MIN_HEADERS 10
44
+
45
+/** scoring settings for score_header */
46
+#define FLAC_HEADER_BASE_SCORE        10
47
+#define FLAC_HEADER_CHANGED_PENALTY   7
48
+#define FLAC_HEADER_CRC_FAIL_PENALTY  50
49
+#define FLAC_HEADER_NOT_PENALIZED_YET 100000
50
+#define FLAC_HEADER_NOT_SCORED_YET    -100000
51
+
52
+/** largest possible size of flac header */
53
+#define MAX_FRAME_HEADER_SIZE 16
54
+
55
+typedef struct FLACHeaderMarker {
56
+    int offset;       /**< byte offset from start of FLACParseContext->buffer */
57
+    int *link_penalty;  /**< pointer to array of local scores between this header
58
+                           and the one at a distance equal array position     */
59
+    int max_score;    /**< maximum score found after checking each child that
60
+                           has a valid CRC                                    */
61
+    FLACFrameInfo fi; /**< decoded frame header info                          */
62
+    struct FLACHeaderMarker *next;       /**< next CRC-8 verified header that
63
+                                              immediately follows this one in
64
+                                              the bytestream                  */
65
+    struct FLACHeaderMarker *best_child; /**< following frame header with
66
+                                              which this frame has the best
67
+                                              score with                      */
68
+} FLACHeaderMarker;
69
+
70
+typedef struct FLACParseContext {
71
+    AVCodecContext *avctx;         /**< codec context pointer for logging     */
72
+    FLACHeaderMarker *headers;     /**< linked-list that starts at the first
73
+                                        CRC-8 verified header within buffer   */
74
+    FLACHeaderMarker *best_header; /**< highest scoring header within buffer  */
75
+    int nb_headers_found;          /**< number of headers found in the last
76
+                                        flac_parse() call                     */
77
+    int best_header_valid;         /**< flag set when the parser returns junk;
78
+                                        if set return best_header next time   */
79
+    AVFifoBuffer *fifo_buf;        /**< buffer to store all data until headers
80
+                                        can be verified                       */
81
+    int end_padded;                /**< specifies if fifo_buf's end is padded */
82
+    uint8_t *wrap_buf;             /**< general fifo read buffer when wrapped */
83
+    int wrap_buf_allocated_size;   /**< actual allocated size of the buffer   */
84
+} FLACParseContext;
85
+
86
+static int frame_header_is_valid(AVCodecContext *avctx, const uint8_t *buf,
87
+                                 FLACFrameInfo *fi)
88
+{
89
+    GetBitContext gb;
90
+    init_get_bits(&gb, buf, MAX_FRAME_HEADER_SIZE * 8);
91
+    return !ff_flac_decode_frame_header(avctx, &gb, fi, 127);
92
+}
93
+
94
+/**
95
+ * Non-destructive fast fifo pointer fetching
96
+ * Returns a pointer from the specified offset.
97
+ * If possible the pointer points within the fifo buffer.
98
+ * Otherwise (if it would cause a wrap around,) a pointer to a user-specified
99
+ * buffer is used.
100
+ * The pointer can be NULL.  In any case it will be reallocated to hold the size.
101
+ * If the returned pointer will be used after subsequent calls to flac_fifo_read_wrap
102
+ * then the subsequent calls should pass in a different wrap_buf so as to not
103
+ * overwrite the contents of the previous wrap_buf.
104
+ * This function is based on av_fifo_generic_read, which is why there is a comment
105
+ * about a memory barrier for SMP.
106
+ */
107
+static uint8_t* flac_fifo_read_wrap(FLACParseContext *fpc, int offset, int len,
108
+                               uint8_t** wrap_buf, int* allocated_size)
109
+{
110
+    AVFifoBuffer *f   = fpc->fifo_buf;
111
+    uint8_t *start    = f->rptr + offset;
112
+    uint8_t *tmp_buf;
113
+
114
+    if (start >= f->end)
115
+        start -= f->end - f->buffer;
116
+    if (f->end - start >= len)
117
+        return start;
118
+
119
+    tmp_buf = av_fast_realloc(*wrap_buf, allocated_size, len);
120
+
121
+    if (!tmp_buf) {
122
+        av_log(fpc->avctx, AV_LOG_ERROR,
123
+               "couldn't reallocate wrap buffer of size %d", len);
124
+        return NULL;
125
+    }
126
+    *wrap_buf = tmp_buf;
127
+    do {
128
+        int seg_len = FFMIN(f->end - start, len);
129
+        memcpy(tmp_buf, start, seg_len);
130
+        tmp_buf = (uint8_t*)tmp_buf + seg_len;
131
+// memory barrier needed for SMP here in theory
132
+
133
+        start += seg_len - (f->end - f->buffer);
134
+        len -= seg_len;
135
+    } while (len > 0);
136
+
137
+    return *wrap_buf;
138
+}
139
+
140
+/**
141
+ * Return a pointer in the fifo buffer where the offset starts at until
142
+ * the wrap point or end of request.
143
+ * len will contain the valid length of the returned buffer.
144
+ * A second call to flac_fifo_read (with new offset and len) should be called
145
+ * to get the post-wrap buf if the returned len is less than the requested.
146
+ **/
147
+static uint8_t* flac_fifo_read(FLACParseContext *fpc, int offset, int *len)
148
+{
149
+    AVFifoBuffer *f   = fpc->fifo_buf;
150
+    uint8_t *start    = f->rptr + offset;
151
+
152
+    if (start >= f->end)
153
+        start -= f->end - f->buffer;
154
+    *len = FFMIN(*len, f->end - start);
155
+    return start;
156
+}
157
+
158
+static int find_headers_search_validate(FLACParseContext *fpc, int offset)
159
+{
160
+    FLACFrameInfo fi;
161
+    uint8_t *header_buf;
162
+    int size = 0;
163
+    header_buf = flac_fifo_read_wrap(fpc, offset,
164
+                                     MAX_FRAME_HEADER_SIZE,
165
+                                     &fpc->wrap_buf,
166
+                                     &fpc->wrap_buf_allocated_size);
167
+    if (frame_header_is_valid(fpc->avctx, header_buf, &fi)) {
168
+        FLACHeaderMarker **end_handle = &fpc->headers;
169
+        int i;
170
+
171
+        size = 0;
172
+        while (*end_handle) {
173
+            end_handle = &(*end_handle)->next;
174
+            size++;
175
+        }
176
+
177
+        *end_handle = av_mallocz(sizeof(FLACHeaderMarker));
178
+        if (!*end_handle) {
179
+            av_log(fpc->avctx, AV_LOG_ERROR,
180
+                   "couldn't allocate FLACHeaderMarker\n");
181
+            return AVERROR(ENOMEM);
182
+        }
183
+        (*end_handle)->fi           = fi;
184
+        (*end_handle)->offset       = offset;
185
+        (*end_handle)->link_penalty = av_malloc(sizeof(int) *
186
+                                            FLAC_MAX_SEQUENTIAL_HEADERS);
187
+        for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++)
188
+            (*end_handle)->link_penalty[i] = FLAC_HEADER_NOT_PENALIZED_YET;
189
+
190
+        fpc->nb_headers_found++;
191
+        size++;
192
+    }
193
+    return size;
194
+}
195
+
196
+static int find_headers_search(FLACParseContext *fpc, uint8_t *buf, int buf_size,
197
+                               int search_start)
198
+
199
+{
200
+    int size = 0, mod_offset = (buf_size - 1) % 4, i, j;
201
+    uint32_t x;
202
+
203
+    for (i = 0; i < mod_offset; i++) {
204
+        if ((AV_RB16(buf + i) & 0xFFFE) == 0xFFF8)
205
+            size = find_headers_search_validate(fpc, search_start + i);
206
+    }
207
+
208
+    for (; i < buf_size - 1; i += 4) {
209
+        x = AV_RB32(buf + i);
210
+        if (((x & ~(x + 0x01010101)) & 0x80808080)) {
211
+            for (j = 0; j < 4; j++) {
212
+                if ((AV_RB16(buf + i + j) & 0xFFFE) == 0xFFF8)
213
+                    size = find_headers_search_validate(fpc, search_start + i + j);
214
+            }
215
+        }
216
+    }
217
+    return size;
218
+}
219
+
220
+static int find_new_headers(FLACParseContext *fpc, int search_start)
221
+{
222
+    FLACHeaderMarker *end;
223
+    int search_end, size = 0, read_len, temp;
224
+    uint8_t *buf;
225
+    fpc->nb_headers_found = 0;
226
+
227
+    /* Search for a new header of at most 16 bytes. */
228
+    search_end = av_fifo_size(fpc->fifo_buf) - (MAX_FRAME_HEADER_SIZE - 1);
229
+    read_len   = search_end - search_start + 1;
230
+    buf        = flac_fifo_read(fpc, search_start, &read_len);
231
+    size       = find_headers_search(fpc, buf, read_len, search_start);
232
+    search_start += read_len - 1;
233
+
234
+    /* If fifo end was hit do the wrap around. */
235
+    if (search_start != search_end) {
236
+        uint8_t wrap[2];
237
+
238
+        wrap[0]  = buf[read_len - 1];
239
+        read_len = search_end - search_start + 1;
240
+
241
+        /* search_start + 1 is the post-wrap offset in the fifo. */
242
+        buf      = flac_fifo_read(fpc, search_start + 1, &read_len);
243
+        wrap[1]  = buf[0];
244
+
245
+        if ((AV_RB16(wrap) & 0xFFFE) == 0xFFF8) {
246
+            temp = find_headers_search_validate(fpc, search_start);
247
+            size = FFMAX(size, temp);
248
+        }
249
+        search_start++;
250
+
251
+        /* Continue to do the last half of the wrap. */
252
+        temp     = find_headers_search(fpc, buf, read_len, search_start);
253
+        size     = FFMAX(size, temp);
254
+        search_start += read_len - 1;
255
+    }
256
+
257
+    /* Return the size even if no new headers were found. */
258
+    if (!size && fpc->headers)
259
+        for (end = fpc->headers; end; end = end->next)
260
+            size++;
261
+    return size;
262
+}
263
+
264
+static int check_header_mismatch(FLACParseContext  *fpc,
265
+                                 FLACHeaderMarker  *header,
266
+                                 FLACHeaderMarker  *child,
267
+                                 int                log_level_offset)
268
+{
269
+    FLACFrameInfo  *header_fi = &header->fi, *child_fi = &child->fi;
270
+    int deduction = 0, deduction_expected = 0, i;
271
+    if (child_fi->samplerate != header_fi->samplerate) {
272
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
273
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
274
+               "sample rate change detected in adjacent frames\n");
275
+    }
276
+    if (child_fi->bps != header_fi->bps) {
277
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
278
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
279
+               "bits per sample change detected in adjacent frames\n");
280
+    }
281
+    if (child_fi->is_var_size != header_fi->is_var_size) {
282
+        /* Changing blocking strategy not allowed per the spec */
283
+        deduction += FLAC_HEADER_BASE_SCORE;
284
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
285
+                   "blocking strategy change detected in adjacent frames\n");
286
+    }
287
+    if (child_fi->channels != header_fi->channels) {
288
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
289
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
290
+                   "number of channels change detected in adjacent frames\n");
291
+    }
292
+    /* Check sample and frame numbers. */
293
+    if ((child_fi->frame_or_sample_num - header_fi->frame_or_sample_num
294
+         != header_fi->blocksize) &&
295
+        (child_fi->frame_or_sample_num
296
+         != header_fi->frame_or_sample_num + 1)) {
297
+        FLACHeaderMarker *curr;
298
+        int expected_frame_num, expected_sample_num;
299
+        /* If there are frames in the middle we expect this deduction,
300
+           as they are probably valid and this one follows it */
301
+
302
+        expected_frame_num = expected_sample_num = header_fi->frame_or_sample_num;
303
+        curr = header;
304
+        while (curr != child) {
305
+            /* Ignore frames that failed all crc checks */
306
+            for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS; i++) {
307
+                if (curr->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY) {
308
+                    expected_frame_num++;
309
+                    expected_sample_num += curr->fi.blocksize;
310
+                    break;
311
+                }
312
+            }
313
+            curr = curr->next;
314
+        }
315
+
316
+        if (expected_frame_num  == child_fi->frame_or_sample_num ||
317
+            expected_sample_num == child_fi->frame_or_sample_num)
318
+            deduction_expected = deduction ? 0 : 1;
319
+
320
+        deduction += FLAC_HEADER_CHANGED_PENALTY;
321
+        av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
322
+                   "sample/frame number mismatch in adjacent frames\n");
323
+    }
324
+
325
+    /* If we have suspicious headers, check the CRC between them */
326
+    if (deduction && !deduction_expected) {
327
+        FLACHeaderMarker *curr;
328
+        int read_len;
329
+        uint8_t *buf;
330
+        uint32_t crc = 1;
331
+        int inverted_test = 0;
332
+
333
+        /* Since CRC is expensive only do it if we haven't yet.
334
+           This assumes a CRC penalty is greater than all other check penalties */
335
+        curr = header->next;
336
+        for (i = 0; i < FLAC_MAX_SEQUENTIAL_HEADERS && curr != child; i++)
337
+            curr = curr->next;
338
+
339
+        if (header->link_penalty[i] < FLAC_HEADER_CRC_FAIL_PENALTY ||
340
+            header->link_penalty[i] == FLAC_HEADER_NOT_PENALIZED_YET) {
341
+            FLACHeaderMarker *start, *end;
342
+
343
+            /* Although overlapping chains are scored, the crc should never
344
+               have to be computed twice for a single byte. */
345
+            start = header;
346
+            end   = child;
347
+            if (i > 0 &&
348
+                header->link_penalty[i - 1] >= FLAC_HEADER_CRC_FAIL_PENALTY) {
349
+                while (start->next != child)
350
+                    start = start->next;
351
+                inverted_test = 1;
352
+            } else if (i > 0 &&
353
+                       header->next->link_penalty[i-1] >=
354
+                       FLAC_HEADER_CRC_FAIL_PENALTY ) {
355
+                end = header->next;
356
+                inverted_test = 1;
357
+            }
358
+
359
+            read_len = end->offset - start->offset;
360
+            buf      = flac_fifo_read(fpc, start->offset, &read_len);
361
+            crc      = av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, buf, read_len);
362
+            read_len = (end->offset - start->offset) - read_len;
363
+
364
+            if (read_len) {
365
+                buf = flac_fifo_read(fpc, end->offset - read_len, &read_len);
366
+                crc = av_crc(av_crc_get_table(AV_CRC_16_ANSI), crc, buf, read_len);
367
+            }
368
+        }
369
+
370
+        if (!crc ^ !inverted_test) {
371
+            deduction += FLAC_HEADER_CRC_FAIL_PENALTY;
372
+            av_log(fpc->avctx, AV_LOG_WARNING + log_level_offset,
373
+                   "crc check failed from offset %i (frame %"PRId64") to %i (frame %"PRId64")\n",
374
+                   header->offset, header_fi->frame_or_sample_num,
375
+                   child->offset, child_fi->frame_or_sample_num);
376
+        }
377
+    }
378
+    return deduction;
379
+}
380
+
381
+/**
382
+ * Score a header.
383
+ *
384
+ * Give FLAC_HEADER_BASE_SCORE points to a frame for existing.
385
+ * If it has children, (subsequent frames of which the preceding CRC footer
386
+ * validates against this one,) then take the maximum score of the children,
387
+ * with a penalty of FLAC_HEADER_CHANGED_PENALTY applied for each change to
388
+ * bps, sample rate, channels, but not decorrelation mode, or blocksize,
389
+ * because it can change often.
390
+ **/
391
+static int score_header(FLACParseContext *fpc, FLACHeaderMarker *header)
392
+{
393
+    FLACHeaderMarker *child;
394
+    int dist = 0;
395
+    int child_score;
396
+
397
+    if (header->max_score != FLAC_HEADER_NOT_SCORED_YET)
398
+        return header->max_score;
399
+
400
+    header->max_score = FLAC_HEADER_BASE_SCORE;
401
+
402
+    /* Check and compute the children's scores. */
403
+    child = header->next;
404
+    for (dist = 0; dist < FLAC_MAX_SEQUENTIAL_HEADERS && child; dist++) {
405
+        /* Look at the child's frame header info and penalize suspicious
406
+           changes between the headers. */
407
+        if (header->link_penalty[dist] == FLAC_HEADER_NOT_PENALIZED_YET) {
408
+            header->link_penalty[dist] = check_header_mismatch(fpc, header,
409
+                                                               child, AV_LOG_DEBUG);
410
+        }
411
+        child_score = score_header(fpc, child) - header->link_penalty[dist];
412
+
413
+        if (FLAC_HEADER_BASE_SCORE + child_score > header->max_score) {
414
+            /* Keep the child because the frame scoring is dynamic. */
415
+            header->best_child = child;
416
+            header->max_score  = FLAC_HEADER_BASE_SCORE + child_score;
417
+        }
418
+        child = child->next;
419
+    }
420
+
421
+    return header->max_score;
422
+}
423
+
424
+static void score_sequences(FLACParseContext *fpc)
425
+{
426
+    FLACHeaderMarker *curr;
427
+    int best_score = FLAC_HEADER_NOT_SCORED_YET;
428
+    /* First pass to clear all old scores. */
429
+    for (curr = fpc->headers; curr; curr = curr->next)
430
+        curr->max_score = FLAC_HEADER_NOT_SCORED_YET;
431
+
432
+    /* Do a second pass to score them all. */
433
+    for (curr = fpc->headers; curr; curr = curr->next) {
434
+        if (score_header(fpc, curr) > best_score) {
435
+            fpc->best_header = curr;
436
+            best_score       = curr->max_score;
437
+        }
438
+    }
439
+}
440
+
441
+static int get_best_header(FLACParseContext* fpc, const uint8_t **poutbuf,
442
+                           int *poutbuf_size)
443
+{
444
+    FLACHeaderMarker *header = fpc->best_header;
445
+    FLACHeaderMarker *child  = header->best_child;
446
+    if (!child) {
447
+        *poutbuf_size = av_fifo_size(fpc->fifo_buf) - header->offset;
448
+    } else {
449
+        *poutbuf_size = child->offset - header->offset;
450
+
451
+        /* If the child has suspicious changes, log them */
452
+        check_header_mismatch(fpc, header, child, 0);
453
+    }
454
+
455
+    fpc->avctx->sample_rate = header->fi.samplerate;
456
+    fpc->avctx->channels    = header->fi.channels;
457
+    fpc->avctx->frame_size  = header->fi.blocksize;
458
+    *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,
459
+                                        &fpc->wrap_buf,
460
+                                        &fpc->wrap_buf_allocated_size);
461
+
462
+    fpc->best_header_valid = 0;
463
+    /* Return the negative overread index so the client can compute pos.
464
+       This should be the amount overread to the beginning of the child */
465
+    if (child)
466
+        return child->offset - av_fifo_size(fpc->fifo_buf);
467
+    return 0;
468
+}
469
+
470
+static int flac_parse(AVCodecParserContext *s, AVCodecContext *avctx,
471
+                      const uint8_t **poutbuf, int *poutbuf_size,
472
+                      const uint8_t *buf, int buf_size)
473
+{
474
+    FLACParseContext *fpc = s->priv_data;
475
+    FLACHeaderMarker *curr;
476
+    int nb_headers;
477
+
478
+    if (s->flags & PARSER_FLAG_COMPLETE_FRAMES) {
479
+        FLACFrameInfo fi;
480
+        if (frame_header_is_valid(avctx, buf, &fi))
481
+            avctx->frame_size = fi.blocksize;
482
+        *poutbuf      = buf;
483
+        *poutbuf_size = buf_size;
484
+        return buf_size;
485
+    }
486
+
487
+    fpc->avctx = avctx;
488
+    if (fpc->best_header_valid)
489
+        return get_best_header(fpc, poutbuf, poutbuf_size);
490
+
491
+    /* If a best_header was found last call remove it with the buffer data. */
492
+    if (fpc->best_header && fpc->best_header->best_child) {
493
+        FLACHeaderMarker *temp;
494
+        FLACHeaderMarker *best_child = fpc->best_header->best_child;
495
+
496
+        /* Remove headers in list until the end of the best_header. */
497
+        for (curr = fpc->headers; curr != best_child; curr = temp) {
498
+            if (curr != fpc->best_header) {
499
+                av_log(avctx, AV_LOG_DEBUG,
500
+                       "dropping low score %i frame header from offset %i to %i\n",
501
+                       curr->max_score, curr->offset, curr->next->offset);
502
+            }
503
+            temp = curr->next;
504
+            av_freep(&curr->link_penalty);
505
+            av_free(curr);
506
+        }
507
+        /* Release returned data from ring buffer. */
508
+        av_fifo_drain(fpc->fifo_buf, best_child->offset);
509
+
510
+        /* Fix the offset for the headers remaining to match the new buffer. */
511
+        for (curr = best_child->next; curr; curr = curr->next)
512
+            curr->offset -= best_child->offset;
513
+
514
+        best_child->offset = 0;
515
+        fpc->headers       = best_child;
516
+        fpc->best_header   = NULL;
517
+    } else if (fpc->best_header) {
518
+        /* No end frame no need to delete the buffer; probably eof */
519
+        FLACHeaderMarker *temp;
520
+
521
+        for (curr = fpc->headers; curr != fpc->best_header; curr = temp) {
522
+            temp = curr->next;
523
+            av_freep(&curr->link_penalty);
524
+            av_free(curr);
525
+        }
526
+        fpc->headers = fpc->best_header->next;
527
+        av_freep(&fpc->best_header->link_penalty);
528
+        av_freep(&fpc->best_header);
529
+    }
530
+
531
+    /* Find and score new headers. */
532
+    if (buf_size || !fpc->end_padded) {
533
+        int start_offset;
534
+
535
+        /* Pad the end once if EOF, to check the final region for headers. */
536
+        if (!buf_size) {
537
+            fpc->end_padded = 1;
538
+            buf_size        = MAX_FRAME_HEADER_SIZE;
539
+        }
540
+
541
+        /* Fill the buffer. */
542
+        if (av_fifo_realloc2(fpc->fifo_buf,
543
+                             buf_size + av_fifo_size(fpc->fifo_buf)) < 0) {
544
+            av_log(avctx, AV_LOG_ERROR,
545
+                   "couldn't reallocate buffer of size %d\n",
546
+                   buf_size + av_fifo_size(fpc->fifo_buf));
547
+            goto handle_error;
548
+        }
549
+
550
+        if (buf) {
551
+            av_fifo_generic_write(fpc->fifo_buf, (void*) buf, buf_size, NULL);
552
+        } else {
553
+            int8_t pad[MAX_FRAME_HEADER_SIZE];
554
+            memset(pad, 0, sizeof(pad));
555
+            av_fifo_generic_write(fpc->fifo_buf, (void*) pad, sizeof(pad), NULL);
556
+        }
557
+
558
+        /* Tag headers and update sequences. */
559
+        start_offset = av_fifo_size(fpc->fifo_buf) -
560
+                       (buf_size + (MAX_FRAME_HEADER_SIZE - 1));
561
+        start_offset = FFMAX(0, start_offset);
562
+        nb_headers   = find_new_headers(fpc, start_offset);
563
+
564
+        /* Wait till FLAC_MIN_HEADERS to output a valid frame. */
565
+        if (!fpc->end_padded && nb_headers < FLAC_MIN_HEADERS)
566
+            goto handle_error;
567
+
568
+        /* If headers found, update the scores since we have longer chains. */
569
+        if (fpc->end_padded || fpc->nb_headers_found)
570
+            score_sequences(fpc);
571
+
572
+        /* restore the state pre-padding */
573
+        if (fpc->end_padded) {
574
+            /* HACK: drain the tail of the fifo */
575
+            fpc->fifo_buf->wptr -= MAX_FRAME_HEADER_SIZE;
576
+            fpc->fifo_buf->wndx -= MAX_FRAME_HEADER_SIZE;
577
+            if (fpc->fifo_buf->wptr < 0) {
578
+                fpc->fifo_buf->wptr += fpc->fifo_buf->end -
579
+                    fpc->fifo_buf->buffer;
580
+            }
581
+            buf_size = 0;
582
+        }
583
+    }
584
+
585
+    curr = fpc->headers;
586
+    for (curr = fpc->headers; curr; curr = curr->next)
587
+        if (!fpc->best_header || curr->max_score > fpc->best_header->max_score)
588
+            fpc->best_header = curr;
589
+
590
+    if (fpc->best_header) {
591
+        fpc->best_header_valid = 1;
592
+        if (fpc->best_header->offset > 0) {
593
+            /* Output a junk frame. */
594
+            av_log(avctx, AV_LOG_DEBUG, "Junk frame till offset %i\n",
595
+                   fpc->best_header->offset);
596
+
597
+            /* Set frame_size to 0. It is unknown or invalid in a junk frame. */
598
+            avctx->frame_size = 0;
599
+            *poutbuf_size     = fpc->best_header->offset;
600
+            *poutbuf          = flac_fifo_read_wrap(fpc, 0, *poutbuf_size,
601
+                                                    &fpc->wrap_buf,
602
+                                                    &fpc->wrap_buf_allocated_size);
603
+            return buf_size ? buf_size : (fpc->best_header->offset -
604
+                                          av_fifo_size(fpc->fifo_buf));
605
+        }
606
+        if (!buf_size)
607
+            return get_best_header(fpc, poutbuf, poutbuf_size);
608
+    }
609
+
610
+handle_error:
611
+    *poutbuf      = NULL;
612
+    *poutbuf_size = 0;
613
+    return buf_size;
614
+}
615
+
616
+static int flac_parse_init(AVCodecParserContext *c)
617
+{
618
+    FLACParseContext *fpc = c->priv_data;
619
+    /* There will generally be FLAC_MIN_HEADERS buffered in the fifo before
620
+       it drains.  8192 is an approximate average size of a flac frame     */
621
+    fpc->fifo_buf = av_fifo_alloc(8192 * FLAC_MIN_HEADERS);
622
+
623
+    return 0;
624
+}
625
+
626
+static void flac_parse_close(AVCodecParserContext *c)
627
+{
628
+    FLACParseContext *fpc = c->priv_data;
629
+    FLACHeaderMarker *curr = fpc->headers, *temp;
630
+
631
+    while (curr) {
632
+        temp = curr->next;
633
+        av_freep(&curr->link_penalty);
634
+        av_free(curr);
635
+        curr = temp;
636
+    }
637
+    av_fifo_free(fpc->fifo_buf);
638
+    av_free(fpc->wrap_buf);
639
+}
640
+
641
+AVCodecParser flac_parser = {
642
+    { CODEC_ID_FLAC },
643
+    sizeof(FLACParseContext),
644
+    flac_parse_init,
645
+    flac_parse,
646
+    flac_parse_close,
647
+};
... ...
@@ -1,27 +1,49 @@
1
-ret: 0         st: 0 flags:1 dts: NOPTS    pts: NOPTS    pos:   8256 size:  1024
2
-ret:-1         st:-1 flags:0  ts:-1.000000
3
-ret:-1         st:-1 flags:1  ts: 1.894167
4
-ret:-1         st: 0 flags:0  ts: 0.788345
1
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
2
+ret: 0         st:-1 flags:0  ts:-1.000000
3
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
4
+ret: 0         st:-1 flags:1  ts: 1.894167
5
+ret: 0         st: 0 flags:1 dts: 1.880816 pts: 1.880816 pos:  86742 size:  2191
6
+ret: 0         st: 0 flags:0  ts: 0.788345
7
+ret: 0         st: 0 flags:1 dts: 0.809796 pts: 0.809796 pos:  27366 size:   615
5 8
 ret:-1         st: 0 flags:1  ts:-0.317506
6
-ret:-1         st:-1 flags:0  ts: 2.576668
7
-ret:-1         st:-1 flags:1  ts: 1.470835
8
-ret:-1         st: 0 flags:0  ts: 0.365011
9
+ret: 0         st:-1 flags:0  ts: 2.576668
10
+ret: 0         st: 0 flags:1 dts: 2.586122 pts: 2.586122 pos: 145606 size:  2384
11
+ret: 0         st:-1 flags:1  ts: 1.470835
12
+ret: 0         st: 0 flags:1 dts: 1.462857 pts: 1.462857 pos:  53388 size:  1851
13
+ret: 0         st: 0 flags:0  ts: 0.365011
14
+ret: 0         st: 0 flags:1 dts: 0.365714 pts: 0.365714 pos:  16890 size:   614
9 15
 ret:-1         st: 0 flags:1  ts:-0.740839
10
-ret:-1         st:-1 flags:0  ts: 2.153336
11
-ret:-1         st:-1 flags:1  ts: 1.047503
12
-ret:-1         st: 0 flags:0  ts:-0.058322
13
-ret:-1         st: 0 flags:1  ts: 2.835828
14
-ret:-1         st:-1 flags:0  ts: 1.730004
15
-ret:-1         st:-1 flags:1  ts: 0.624171
16
-ret:-1         st: 0 flags:0  ts:-0.481655
17
-ret:-1         st: 0 flags:1  ts: 2.412494
18
-ret:-1         st:-1 flags:0  ts: 1.306672
19
-ret:-1         st:-1 flags:1  ts: 0.200839
20
-ret:-1         st: 0 flags:0  ts:-0.904989
21
-ret:-1         st: 0 flags:1  ts: 1.989184
22
-ret:-1         st:-1 flags:0  ts: 0.883340
16
+ret: 0         st:-1 flags:0  ts: 2.153336
17
+ret: 0         st: 0 flags:1 dts: 2.168163 pts: 2.168163 pos: 110531 size:  2143
18
+ret: 0         st:-1 flags:1  ts: 1.047503
19
+ret: 0         st: 0 flags:1 dts: 1.044898 pts: 1.044898 pos:  32880 size:   579
20
+ret: 0         st: 0 flags:0  ts:-0.058322
21
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
22
+ret: 0         st: 0 flags:1  ts: 2.835828
23
+ret: 0         st: 0 flags:1 dts: 2.821224 pts: 2.821224 pos: 167112 size:  2391
24
+ret: 0         st:-1 flags:0  ts: 1.730004
25
+ret: 0         st: 0 flags:1 dts: 1.750204 pts: 1.750204 pos:  75788 size:  2191
26
+ret: 0         st:-1 flags:1  ts: 0.624171
27
+ret: 0         st: 0 flags:1 dts: 0.600816 pts: 0.600816 pos:  22446 size:   616
28
+ret: 0         st: 0 flags:0  ts:-0.481655
29
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
30
+ret: 0         st: 0 flags:1  ts: 2.412494
31
+ret: 0         st: 0 flags:1 dts: 2.403265 pts: 2.403265 pos: 129793 size:  2138
32
+ret: 0         st:-1 flags:0  ts: 1.306672
33
+ret: 0         st: 0 flags:1 dts: 1.332245 pts: 1.332245 pos:  44812 size:  1609
34
+ret: 0         st:-1 flags:1  ts: 0.200839
35
+ret: 0         st: 0 flags:1 dts: 0.182857 pts: 0.182857 pos:  12572 size:   628
36
+ret: 0         st: 0 flags:0  ts:-0.904989
37
+ret: 0         st: 0 flags:1 dts: 0.000000 pts: 0.000000 pos:   8256 size:   614
38
+ret: 0         st: 0 flags:1  ts: 1.989184
39
+ret: 0         st: 0 flags:1 dts: 1.985306 pts: 1.985306 pos:  95508 size:  2169
40
+ret: 0         st:-1 flags:0  ts: 0.883340
41
+ret: 0         st: 0 flags:1 dts: 0.888163 pts: 0.888163 pos:  29211 size:   620
23 42
 ret:-1         st:-1 flags:1  ts:-0.222493
24
-ret:-1         st: 0 flags:0  ts: 2.671678
25
-ret:-1         st: 0 flags:1  ts: 1.565850
26
-ret:-1         st:-1 flags:0  ts: 0.460008
43
+ret: 0         st: 0 flags:0  ts: 2.671678
44
+ret: 0         st: 0 flags:1 dts: 2.690612 pts: 2.690612 pos: 155154 size:  2394
45
+ret: 0         st: 0 flags:1  ts: 1.565850
46
+ret: 0         st: 0 flags:1 dts: 1.541224 pts: 1.541224 pos:  59082 size:  1974
47
+ret: 0         st:-1 flags:0  ts: 0.460008
48
+ret: 0         st: 0 flags:1 dts: 0.470204 pts: 0.470204 pos:  19353 size:   608
27 49
 ret:-1         st:-1 flags:1  ts:-0.645825