LCOV - code coverage report
Current view: top level - libavcodec - flac_parser.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 290 343 84.5 %
Date: 2017-12-16 13:57:32 Functions: 14 14 100.0 %

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

Generated by: LCOV version 1.13