LCOV - code coverage report
Current view: top level - libavformat - flvdec.c (source / functions) Hit Total Coverage
Test: coverage.info Lines: 487 803 60.6 %
Date: 2017-12-17 23:02:56 Functions: 20 23 87.0 %

          Line data    Source code
       1             : /*
       2             :  * FLV demuxer
       3             :  * Copyright (c) 2003 The FFmpeg Project
       4             :  *
       5             :  * This demuxer will generate a 1 byte extradata for VP6F content.
       6             :  * It is composed of:
       7             :  *  - upper 4 bits: difference between encoded width and visible width
       8             :  *  - lower 4 bits: difference between encoded height and visible height
       9             :  *
      10             :  * This file is part of FFmpeg.
      11             :  *
      12             :  * FFmpeg is free software; you can redistribute it and/or
      13             :  * modify it under the terms of the GNU Lesser General Public
      14             :  * License as published by the Free Software Foundation; either
      15             :  * version 2.1 of the License, or (at your option) any later version.
      16             :  *
      17             :  * FFmpeg is distributed in the hope that it will be useful,
      18             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      19             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      20             :  * Lesser General Public License for more details.
      21             :  *
      22             :  * You should have received a copy of the GNU Lesser General Public
      23             :  * License along with FFmpeg; if not, write to the Free Software
      24             :  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
      25             :  */
      26             : 
      27             : #include "libavutil/avstring.h"
      28             : #include "libavutil/channel_layout.h"
      29             : #include "libavutil/dict.h"
      30             : #include "libavutil/opt.h"
      31             : #include "libavutil/intfloat.h"
      32             : #include "libavutil/mathematics.h"
      33             : #include "libavcodec/bytestream.h"
      34             : #include "libavcodec/mpeg4audio.h"
      35             : #include "avformat.h"
      36             : #include "internal.h"
      37             : #include "avio_internal.h"
      38             : #include "flv.h"
      39             : 
      40             : #define VALIDATE_INDEX_TS_THRESH 2500
      41             : 
      42             : #define RESYNC_BUFFER_SIZE (1<<20)
      43             : 
      44             : typedef struct FLVContext {
      45             :     const AVClass *class; ///< Class for private options.
      46             :     int trust_metadata;   ///< configure streams according onMetaData
      47             :     int wrong_dts;        ///< wrong dts due to negative cts
      48             :     uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
      49             :     int new_extradata_size[FLV_STREAM_TYPE_NB];
      50             :     int last_sample_rate;
      51             :     int last_channels;
      52             :     struct {
      53             :         int64_t dts;
      54             :         int64_t pos;
      55             :     } validate_index[2];
      56             :     int validate_next;
      57             :     int validate_count;
      58             :     int searched_for_end;
      59             : 
      60             :     uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
      61             : 
      62             :     int broken_sizes;
      63             :     int sum_flv_tag_size;
      64             : 
      65             :     int last_keyframe_stream_index;
      66             :     int keyframe_count;
      67             :     int64_t video_bit_rate;
      68             :     int64_t audio_bit_rate;
      69             :     int64_t *keyframe_times;
      70             :     int64_t *keyframe_filepositions;
      71             :     int missing_streams;
      72             :     AVRational framerate;
      73             : } FLVContext;
      74             : 
      75       12260 : static int probe(AVProbeData *p, int live)
      76             : {
      77       12260 :     const uint8_t *d = p->buf;
      78       12260 :     unsigned offset = AV_RB32(d + 5);
      79             : 
      80       12356 :     if (d[0] == 'F' &&
      81         152 :         d[1] == 'L' &&
      82         112 :         d[2] == 'V' &&
      83         168 :         d[3] < 5 && d[5] == 0 &&
      84         112 :         offset + 100 < p->buf_size &&
      85             :         offset > 8) {
      86          56 :         int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
      87             : 
      88          56 :         if (live == is_live)
      89          28 :             return AVPROBE_SCORE_MAX;
      90             :     }
      91       12232 :     return 0;
      92             : }
      93             : 
      94        6130 : static int flv_probe(AVProbeData *p)
      95             : {
      96        6130 :     return probe(p, 0);
      97             : }
      98             : 
      99        6130 : static int live_flv_probe(AVProbeData *p)
     100             : {
     101        6130 :     return probe(p, 1);
     102             : }
     103             : 
     104          32 : static void add_keyframes_index(AVFormatContext *s)
     105             : {
     106          32 :     FLVContext *flv   = s->priv_data;
     107          32 :     AVStream *stream  = NULL;
     108          32 :     unsigned int i    = 0;
     109             : 
     110          32 :     if (flv->last_keyframe_stream_index < 0) {
     111           2 :         av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
     112           2 :         return;
     113             :     }
     114             : 
     115          30 :     av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
     116          30 :     stream = s->streams[flv->last_keyframe_stream_index];
     117             : 
     118          30 :     if (stream->nb_index_entries == 0) {
     119         183 :         for (i = 0; i < flv->keyframe_count; i++) {
     120         306 :             av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
     121         306 :                    flv->keyframe_filepositions[i], flv->keyframe_times[i] * 1000);
     122         153 :             av_add_index_entry(stream, flv->keyframe_filepositions[i],
     123         153 :                 flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
     124             :         }
     125             :     } else
     126           0 :         av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
     127             : 
     128          30 :     if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
     129          22 :         av_freep(&flv->keyframe_times);
     130          22 :         av_freep(&flv->keyframe_filepositions);
     131          22 :         flv->keyframe_count = 0;
     132             :     }
     133             : }
     134             : 
     135          30 : static AVStream *create_stream(AVFormatContext *s, int codec_type)
     136             : {
     137          30 :     FLVContext *flv   = s->priv_data;
     138          30 :     AVStream *st = avformat_new_stream(s, NULL);
     139          30 :     if (!st)
     140           0 :         return NULL;
     141          30 :     st->codecpar->codec_type = codec_type;
     142          30 :     if (s->nb_streams>=3 ||(   s->nb_streams==2
     143           2 :                            && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
     144           2 :                            && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE))
     145           2 :         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
     146          30 :     if (codec_type == AVMEDIA_TYPE_AUDIO) {
     147           8 :         st->codecpar->bit_rate = flv->audio_bit_rate;
     148           8 :         flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
     149             :     }
     150          30 :     if (codec_type == AVMEDIA_TYPE_VIDEO) {
     151          22 :         st->codecpar->bit_rate = flv->video_bit_rate;
     152          22 :         flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
     153          22 :         st->avg_frame_rate = flv->framerate;
     154             :     }
     155             : 
     156             : 
     157          30 :     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
     158          30 :     flv->last_keyframe_stream_index = s->nb_streams - 1;
     159          30 :     add_keyframes_index(s);
     160          30 :     return st;
     161             : }
     162             : 
     163        2470 : static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
     164             : {
     165        2470 :     int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
     166        2470 :     int flv_codecid           = flags & FLV_AUDIO_CODECID_MASK;
     167             :     int codec_id;
     168             : 
     169        2470 :     if (!apar->codec_id && !apar->codec_tag)
     170           0 :         return 1;
     171             : 
     172        2470 :     if (apar->bits_per_coded_sample != bits_per_coded_sample)
     173           0 :         return 0;
     174             : 
     175        2470 :     switch (flv_codecid) {
     176             :     // no distinction between S16 and S8 PCM codec flags
     177           0 :     case FLV_CODECID_PCM:
     178           0 :         codec_id = bits_per_coded_sample == 8
     179             :                    ? AV_CODEC_ID_PCM_U8
     180             : #if HAVE_BIGENDIAN
     181             :                    : AV_CODEC_ID_PCM_S16BE;
     182             : #else
     183           0 :                    : AV_CODEC_ID_PCM_S16LE;
     184             : #endif
     185           0 :         return codec_id == apar->codec_id;
     186           0 :     case FLV_CODECID_PCM_LE:
     187           0 :         codec_id = bits_per_coded_sample == 8
     188             :                    ? AV_CODEC_ID_PCM_U8
     189           0 :                    : AV_CODEC_ID_PCM_S16LE;
     190           0 :         return codec_id == apar->codec_id;
     191         253 :     case FLV_CODECID_AAC:
     192         253 :         return apar->codec_id == AV_CODEC_ID_AAC;
     193         522 :     case FLV_CODECID_ADPCM:
     194         522 :         return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
     195           0 :     case FLV_CODECID_SPEEX:
     196           0 :         return apar->codec_id == AV_CODEC_ID_SPEEX;
     197           0 :     case FLV_CODECID_MP3:
     198           0 :         return apar->codec_id == AV_CODEC_ID_MP3;
     199        1695 :     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
     200             :     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
     201             :     case FLV_CODECID_NELLYMOSER:
     202        1695 :         return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
     203           0 :     case FLV_CODECID_PCM_MULAW:
     204           0 :         return apar->sample_rate == 8000 &&
     205           0 :                apar->codec_id    == AV_CODEC_ID_PCM_MULAW;
     206           0 :     case FLV_CODECID_PCM_ALAW:
     207           0 :         return apar->sample_rate == 8000 &&
     208           0 :                apar->codec_id    == AV_CODEC_ID_PCM_ALAW;
     209           0 :     default:
     210           0 :         return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
     211             :     }
     212             : }
     213             : 
     214        2478 : static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
     215             :                                 AVCodecParameters *apar, int flv_codecid)
     216             : {
     217        2478 :     switch (flv_codecid) {
     218             :     // no distinction between S16 and S8 PCM codec flags
     219           0 :     case FLV_CODECID_PCM:
     220           0 :         apar->codec_id = apar->bits_per_coded_sample == 8
     221             :                            ? AV_CODEC_ID_PCM_U8
     222             : #if HAVE_BIGENDIAN
     223             :                            : AV_CODEC_ID_PCM_S16BE;
     224             : #else
     225           0 :                            : AV_CODEC_ID_PCM_S16LE;
     226             : #endif
     227           0 :         break;
     228           0 :     case FLV_CODECID_PCM_LE:
     229           0 :         apar->codec_id = apar->bits_per_coded_sample == 8
     230             :                            ? AV_CODEC_ID_PCM_U8
     231           0 :                            : AV_CODEC_ID_PCM_S16LE;
     232           0 :         break;
     233         254 :     case FLV_CODECID_AAC:
     234         254 :         apar->codec_id = AV_CODEC_ID_AAC;
     235         254 :         break;
     236         526 :     case FLV_CODECID_ADPCM:
     237         526 :         apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
     238         526 :         break;
     239           0 :     case FLV_CODECID_SPEEX:
     240           0 :         apar->codec_id    = AV_CODEC_ID_SPEEX;
     241           0 :         apar->sample_rate = 16000;
     242           0 :         break;
     243           0 :     case FLV_CODECID_MP3:
     244           0 :         apar->codec_id      = AV_CODEC_ID_MP3;
     245           0 :         astream->need_parsing = AVSTREAM_PARSE_FULL;
     246           0 :         break;
     247           0 :     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
     248             :         // in case metadata does not otherwise declare samplerate
     249           0 :         apar->sample_rate = 8000;
     250           0 :         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
     251           0 :         break;
     252         376 :     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
     253         376 :         apar->sample_rate = 16000;
     254         376 :         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
     255         376 :         break;
     256        1322 :     case FLV_CODECID_NELLYMOSER:
     257        1322 :         apar->codec_id = AV_CODEC_ID_NELLYMOSER;
     258        1322 :         break;
     259           0 :     case FLV_CODECID_PCM_MULAW:
     260           0 :         apar->sample_rate = 8000;
     261           0 :         apar->codec_id    = AV_CODEC_ID_PCM_MULAW;
     262           0 :         break;
     263           0 :     case FLV_CODECID_PCM_ALAW:
     264           0 :         apar->sample_rate = 8000;
     265           0 :         apar->codec_id    = AV_CODEC_ID_PCM_ALAW;
     266           0 :         break;
     267           0 :     default:
     268           0 :         avpriv_request_sample(s, "Audio codec (%x)",
     269             :                flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
     270           0 :         apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
     271             :     }
     272        2478 : }
     273             : 
     274        2135 : static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
     275             : {
     276        2135 :     int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
     277             : 
     278        2135 :     if (!vpar->codec_id && !vpar->codec_tag)
     279           0 :         return 1;
     280             : 
     281        2135 :     switch (flv_codecid) {
     282         552 :     case FLV_CODECID_H263:
     283         552 :         return vpar->codec_id == AV_CODEC_ID_FLV1;
     284         271 :     case FLV_CODECID_SCREEN:
     285         271 :         return vpar->codec_id == AV_CODEC_ID_FLASHSV;
     286         196 :     case FLV_CODECID_SCREEN2:
     287         196 :         return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
     288         173 :     case FLV_CODECID_VP6:
     289         173 :         return vpar->codec_id == AV_CODEC_ID_VP6F;
     290           0 :     case FLV_CODECID_VP6A:
     291           0 :         return vpar->codec_id == AV_CODEC_ID_VP6A;
     292         943 :     case FLV_CODECID_H264:
     293         943 :         return vpar->codec_id == AV_CODEC_ID_H264;
     294           0 :     default:
     295           0 :         return vpar->codec_tag == flv_codecid;
     296             :     }
     297             : }
     298             : 
     299        1869 : static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
     300             :                                int flv_codecid, int read)
     301             : {
     302        1869 :     int ret = 0;
     303        1869 :     AVCodecParameters *par = vstream->codecpar;
     304        1869 :     enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
     305        1869 :     switch (flv_codecid) {
     306         561 :     case FLV_CODECID_H263:
     307         561 :         par->codec_id = AV_CODEC_ID_FLV1;
     308         561 :         break;
     309           0 :     case FLV_CODECID_REALH263:
     310           0 :         par->codec_id = AV_CODEC_ID_H263;
     311           0 :         break; // Really mean it this time
     312         276 :     case FLV_CODECID_SCREEN:
     313         276 :         par->codec_id = AV_CODEC_ID_FLASHSV;
     314         276 :         break;
     315         200 :     case FLV_CODECID_SCREEN2:
     316         200 :         par->codec_id = AV_CODEC_ID_FLASHSV2;
     317         200 :         break;
     318         174 :     case FLV_CODECID_VP6:
     319         174 :         par->codec_id = AV_CODEC_ID_VP6F;
     320         174 :     case FLV_CODECID_VP6A:
     321         174 :         if (flv_codecid == FLV_CODECID_VP6A)
     322           0 :             par->codec_id = AV_CODEC_ID_VP6A;
     323         174 :         if (read) {
     324         174 :             if (par->extradata_size != 1) {
     325           1 :                 ff_alloc_extradata(par, 1);
     326             :             }
     327         174 :             if (par->extradata)
     328         174 :                 par->extradata[0] = avio_r8(s->pb);
     329             :             else
     330           0 :                 avio_skip(s->pb, 1);
     331             :         }
     332         174 :         ret = 1;     // 1 byte body size adjustment for flv_read_packet()
     333         174 :         break;
     334         658 :     case FLV_CODECID_H264:
     335         658 :         par->codec_id = AV_CODEC_ID_H264;
     336         658 :         vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
     337         658 :         ret = 3;     // not 4, reading packet type will consume one byte
     338         658 :         break;
     339           0 :     case FLV_CODECID_MPEG4:
     340           0 :         par->codec_id = AV_CODEC_ID_MPEG4;
     341           0 :         ret = 3;
     342           0 :         break;
     343           0 :     default:
     344           0 :         avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
     345           0 :         par->codec_tag = flv_codecid;
     346             :     }
     347             : 
     348        1869 :     if (!vstream->internal->need_context_update && par->codec_id != old_codec_id) {
     349           0 :         avpriv_request_sample(s, "Changing the codec id midstream");
     350           0 :         return AVERROR_PATCHWELCOME;
     351             :     }
     352             : 
     353        1869 :     return ret;
     354             : }
     355             : 
     356         314 : static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
     357             : {
     358         314 :     int length = avio_rb16(ioc);
     359         314 :     if (length >= buffsize) {
     360           0 :         avio_skip(ioc, length);
     361           0 :         return -1;
     362             :     }
     363             : 
     364         314 :     avio_read(ioc, buffer, length);
     365             : 
     366         314 :     buffer[length] = '\0';
     367             : 
     368         314 :     return length;
     369             : }
     370             : 
     371           2 : static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
     372             : {
     373           2 :     FLVContext *flv       = s->priv_data;
     374           2 :     unsigned int timeslen = 0, fileposlen = 0, i;
     375             :     char str_val[256];
     376           2 :     int64_t *times         = NULL;
     377           2 :     int64_t *filepositions = NULL;
     378           2 :     int ret                = AVERROR(ENOSYS);
     379           2 :     int64_t initial_pos    = avio_tell(ioc);
     380             : 
     381           2 :     if (flv->keyframe_count > 0) {
     382           0 :         av_log(s, AV_LOG_DEBUG, "keyframes have been paresed\n");
     383           0 :         return 0;
     384             :     }
     385           2 :     av_assert0(!flv->keyframe_times);
     386           2 :     av_assert0(!flv->keyframe_filepositions);
     387             : 
     388           2 :     if (s->flags & AVFMT_FLAG_IGNIDX)
     389           0 :         return 0;
     390             : 
     391          10 :     while (avio_tell(ioc) < max_pos - 2 &&
     392           4 :            amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
     393             :         int64_t **current_array;
     394             :         unsigned int arraylen;
     395             : 
     396             :         // Expect array object in context
     397           4 :         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
     398           0 :             break;
     399             : 
     400           4 :         arraylen = avio_rb32(ioc);
     401           4 :         if (arraylen>>28)
     402           0 :             break;
     403             : 
     404           4 :         if       (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
     405           2 :             current_array = &times;
     406           2 :             timeslen      = arraylen;
     407           4 :         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
     408           2 :                    !filepositions) {
     409           2 :             current_array = &filepositions;
     410           2 :             fileposlen    = arraylen;
     411             :         } else
     412             :             // unexpected metatag inside keyframes, will not use such
     413             :             // metadata for indexing
     414             :             break;
     415             : 
     416           4 :         if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
     417           0 :             ret = AVERROR(ENOMEM);
     418           0 :             goto finish;
     419             :         }
     420             : 
     421         310 :         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
     422         306 :             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
     423           0 :                 goto invalid;
     424         306 :             current_array[0][i] = av_int2double(avio_rb64(ioc));
     425             :         }
     426           4 :         if (times && filepositions) {
     427             :             // All done, exiting at a position allowing amf_parse_object
     428             :             // to finish parsing the object
     429           2 :             ret = 0;
     430           2 :             break;
     431             :         }
     432             :     }
     433             : 
     434           4 :     if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
     435           6 :         for (i = 0; i < FFMIN(2,fileposlen); i++) {
     436           4 :             flv->validate_index[i].pos = filepositions[i];
     437           4 :             flv->validate_index[i].dts = times[i] * 1000;
     438           4 :             flv->validate_count        = i + 1;
     439             :         }
     440           2 :         flv->keyframe_times = times;
     441           2 :         flv->keyframe_filepositions = filepositions;
     442           2 :         flv->keyframe_count = timeslen;
     443           2 :         times = NULL;
     444           2 :         filepositions = NULL;
     445             :     } else {
     446           0 : invalid:
     447           0 :         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
     448             :     }
     449             : 
     450           2 : finish:
     451           2 :     av_freep(&times);
     452           2 :     av_freep(&filepositions);
     453           2 :     avio_seek(ioc, initial_pos, SEEK_SET);
     454           2 :     return ret;
     455             : }
     456             : 
     457         577 : static int amf_parse_object(AVFormatContext *s, AVStream *astream,
     458             :                             AVStream *vstream, const char *key,
     459             :                             int64_t max_pos, int depth)
     460             : {
     461             :     AVCodecParameters *apar, *vpar;
     462         577 :     FLVContext *flv = s->priv_data;
     463             :     AVIOContext *ioc;
     464             :     AMFDataType amf_type;
     465             :     char str_val[1024];
     466             :     double num_val;
     467             : 
     468         577 :     num_val  = 0;
     469         577 :     ioc      = s->pb;
     470         577 :     amf_type = avio_r8(ioc);
     471             : 
     472         577 :     switch (amf_type) {
     473         514 :     case AMF_DATA_TYPE_NUMBER:
     474         514 :         num_val = av_int2double(avio_rb64(ioc));
     475         514 :         break;
     476          18 :     case AMF_DATA_TYPE_BOOL:
     477          18 :         num_val = avio_r8(ioc);
     478          18 :         break;
     479           9 :     case AMF_DATA_TYPE_STRING:
     480           9 :         if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
     481           0 :             av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
     482           0 :             return -1;
     483             :         }
     484           9 :         break;
     485           2 :     case AMF_DATA_TYPE_OBJECT:
     486           4 :         if (key &&
     487           4 :             (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
     488           4 :             !strcmp(KEYFRAMES_TAG, key) && depth == 1)
     489           2 :             if (parse_keyframes_index(s, ioc,
     490             :                                       max_pos) < 0)
     491           0 :                 av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
     492             :             else
     493           2 :                 add_keyframes_index(s);
     494          14 :         while (avio_tell(ioc) < max_pos - 2 &&
     495           6 :                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
     496           4 :             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
     497             :                                  depth + 1) < 0)
     498           0 :                 return -1;     // if we couldn't skip, bomb out.
     499           2 :         if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
     500           0 :             av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
     501           0 :             return -1;
     502             :         }
     503           2 :         break;
     504           0 :     case AMF_DATA_TYPE_NULL:
     505             :     case AMF_DATA_TYPE_UNDEFINED:
     506             :     case AMF_DATA_TYPE_UNSUPPORTED:
     507           0 :         break;     // these take up no additional space
     508          28 :     case AMF_DATA_TYPE_MIXEDARRAY:
     509             :     {
     510             :         unsigned v;
     511          28 :         avio_skip(ioc, 4);     // skip 32-bit max array index
     512         295 :         while (avio_tell(ioc) < max_pos - 2 &&
     513         267 :                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
     514             :             // this is the only case in which we would want a nested
     515             :             // parse to not skip over the object
     516         239 :             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
     517             :                                  depth + 1) < 0)
     518           0 :                 return -1;
     519          28 :         v = avio_r8(ioc);
     520          28 :         if (v != AMF_END_OF_OBJECT) {
     521           0 :             av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
     522           0 :             return -1;
     523             :         }
     524          28 :         break;
     525             :     }
     526           5 :     case AMF_DATA_TYPE_ARRAY:
     527             :     {
     528             :         unsigned int arraylen, i;
     529             : 
     530           5 :         arraylen = avio_rb32(ioc);
     531         311 :         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
     532         306 :             if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
     533             :                                  depth + 1) < 0)
     534           0 :                 return -1;      // if we couldn't skip, bomb out.
     535             :     }
     536           5 :     break;
     537           1 :     case AMF_DATA_TYPE_DATE:
     538           1 :         avio_skip(ioc, 8 + 2);  // timestamp (double) and UTC offset (int16)
     539           1 :         break;
     540           0 :     default:                    // unsupported type, we couldn't skip
     541           0 :         av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
     542           0 :         return -1;
     543             :     }
     544             : 
     545         577 :     if (key) {
     546         271 :         apar = astream ? astream->codecpar : NULL;
     547         271 :         vpar = vstream ? vstream->codecpar : NULL;
     548             : 
     549             :         // stream info doesn't live any deeper than the first object
     550         271 :         if (depth == 1) {
     551         239 :             if (amf_type == AMF_DATA_TYPE_NUMBER ||
     552             :                 amf_type == AMF_DATA_TYPE_BOOL) {
     553         226 :                 if (!strcmp(key, "duration"))
     554          28 :                     s->duration = num_val * AV_TIME_BASE;
     555         220 :                 else if (!strcmp(key, "videodatarate") &&
     556          22 :                          0 <= (int)(num_val * 1024.0))
     557          22 :                     flv->video_bit_rate = num_val * 1024.0;
     558         184 :                 else if (!strcmp(key, "audiodatarate") &&
     559           8 :                          0 <= (int)(num_val * 1024.0))
     560           8 :                     flv->audio_bit_rate = num_val * 1024.0;
     561         168 :                 else if (!strcmp(key, "datastream")) {
     562           0 :                     AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
     563           0 :                     if (!st)
     564           0 :                         return AVERROR(ENOMEM);
     565           0 :                     st->codecpar->codec_id = AV_CODEC_ID_TEXT;
     566         168 :                 } else if (!strcmp(key, "framerate")) {
     567          22 :                     flv->framerate = av_d2q(num_val, 1000);
     568          22 :                     if (vstream)
     569           0 :                         vstream->avg_frame_rate = flv->framerate;
     570         146 :                 } else if (flv->trust_metadata) {
     571           0 :                     if (!strcmp(key, "videocodecid") && vpar) {
     572           0 :                         int ret = flv_set_video_codec(s, vstream, num_val, 0);
     573           0 :                         if (ret < 0)
     574           0 :                             return ret;
     575           0 :                     } else if (!strcmp(key, "audiocodecid") && apar) {
     576           0 :                         int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
     577           0 :                         flv_set_audio_codec(s, astream, apar, id);
     578           0 :                     } else if (!strcmp(key, "audiosamplerate") && apar) {
     579           0 :                         apar->sample_rate = num_val;
     580           0 :                     } else if (!strcmp(key, "audiosamplesize") && apar) {
     581           0 :                         apar->bits_per_coded_sample = num_val;
     582           0 :                     } else if (!strcmp(key, "stereo") && apar) {
     583           0 :                         apar->channels       = num_val + 1;
     584           0 :                         apar->channel_layout = apar->channels == 2 ?
     585           0 :                                                AV_CH_LAYOUT_STEREO :
     586             :                                                AV_CH_LAYOUT_MONO;
     587           0 :                     } else if (!strcmp(key, "width") && vpar) {
     588           0 :                         vpar->width = num_val;
     589           0 :                     } else if (!strcmp(key, "height") && vpar) {
     590           0 :                         vpar->height = num_val;
     591             :                     }
     592             :                 }
     593             :             }
     594         239 :             if (amf_type == AMF_DATA_TYPE_STRING) {
     595           9 :                 if (!strcmp(key, "encoder")) {
     596           3 :                     int version = -1;
     597           3 :                     if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
     598           0 :                         if (version > 0 && version <= 655)
     599           0 :                             flv->broken_sizes = 1;
     600             :                     }
     601           6 :                 } else if (!strcmp(key, "metadatacreator") && !strcmp(str_val, "MEGA")) {
     602           0 :                     flv->broken_sizes = 1;
     603             :                 }
     604             :             }
     605             :         }
     606             : 
     607         271 :         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
     608           0 :            ((!apar && !strcmp(key, "audiocodecid")) ||
     609           0 :             (!vpar && !strcmp(key, "videocodecid"))))
     610           0 :                 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
     611             : 
     612         514 :         if (!strcmp(key, "duration")        ||
     613         459 :             !strcmp(key, "filesize")        ||
     614         410 :             !strcmp(key, "width")           ||
     615         366 :             !strcmp(key, "height")          ||
     616         322 :             !strcmp(key, "videodatarate")   ||
     617         278 :             !strcmp(key, "framerate")       ||
     618         234 :             !strcmp(key, "videocodecid")    ||
     619         204 :             !strcmp(key, "audiodatarate")   ||
     620         189 :             !strcmp(key, "audiosamplerate") ||
     621         175 :             !strcmp(key, "audiosamplesize") ||
     622         161 :             !strcmp(key, "stereo")          ||
     623         146 :             !strcmp(key, "audiocodecid")    ||
     624          69 :             !strcmp(key, "datastream"))
     625         202 :             return 0;
     626             : 
     627          69 :         s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
     628          69 :         if (amf_type == AMF_DATA_TYPE_BOOL) {
     629          11 :             av_strlcpy(str_val, num_val > 0 ? "true" : "false",
     630             :                        sizeof(str_val));
     631          11 :             av_dict_set(&s->metadata, key, str_val, 0);
     632          58 :         } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
     633          13 :             snprintf(str_val, sizeof(str_val), "%.f", num_val);
     634          13 :             av_dict_set(&s->metadata, key, str_val, 0);
     635          45 :         } else if (amf_type == AMF_DATA_TYPE_STRING)
     636           9 :             av_dict_set(&s->metadata, key, str_val, 0);
     637             :     }
     638             : 
     639         375 :     return 0;
     640             : }
     641             : 
     642             : #define TYPE_ONTEXTDATA 1
     643             : #define TYPE_ONCAPTION 2
     644             : #define TYPE_ONCAPTIONINFO 3
     645             : #define TYPE_UNKNOWN 9
     646             : 
     647          28 : static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
     648             : {
     649          28 :     FLVContext *flv = s->priv_data;
     650             :     AMFDataType type;
     651             :     AVStream *stream, *astream, *vstream;
     652             :     AVStream av_unused *dstream;
     653             :     AVIOContext *ioc;
     654             :     int i;
     655             :     // only needs to hold the string "onMetaData".
     656             :     // Anything longer is something we don't want.
     657             :     char buffer[32];
     658             : 
     659          28 :     astream = NULL;
     660          28 :     vstream = NULL;
     661          28 :     dstream = NULL;
     662          28 :     ioc     = s->pb;
     663             : 
     664             :     // first object needs to be "onMetaData" string
     665          28 :     type = avio_r8(ioc);
     666          56 :     if (type != AMF_DATA_TYPE_STRING ||
     667          28 :         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
     668           0 :         return TYPE_UNKNOWN;
     669             : 
     670          28 :     if (!strcmp(buffer, "onTextData"))
     671           0 :         return TYPE_ONTEXTDATA;
     672             : 
     673          28 :     if (!strcmp(buffer, "onCaption"))
     674           0 :         return TYPE_ONCAPTION;
     675             : 
     676          28 :     if (!strcmp(buffer, "onCaptionInfo"))
     677           0 :         return TYPE_ONCAPTIONINFO;
     678             : 
     679          28 :     if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
     680           0 :         av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
     681           0 :         return TYPE_UNKNOWN;
     682             :     }
     683             : 
     684             :     // find the streams now so that amf_parse_object doesn't need to do
     685             :     // the lookup every time it is called.
     686          28 :     for (i = 0; i < s->nb_streams; i++) {
     687           0 :         stream = s->streams[i];
     688           0 :         if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
     689           0 :             vstream = stream;
     690           0 :             flv->last_keyframe_stream_index = i;
     691           0 :         } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
     692           0 :             astream = stream;
     693           0 :             if (flv->last_keyframe_stream_index == -1)
     694           0 :                 flv->last_keyframe_stream_index = i;
     695             :         }
     696           0 :         else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
     697           0 :             dstream = stream;
     698             :     }
     699             : 
     700             :     // parse the second object (we want a mixed array)
     701          28 :     if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
     702           0 :         return -1;
     703             : 
     704          28 :     return 0;
     705             : }
     706             : 
     707          28 : static int flv_read_header(AVFormatContext *s)
     708             : {
     709             :     int flags;
     710          28 :     FLVContext *flv = s->priv_data;
     711             :     int offset;
     712          28 :     int pre_tag_size = 0;
     713             : 
     714          28 :     avio_skip(s->pb, 4);
     715          28 :     flags = avio_r8(s->pb);
     716             : 
     717          28 :     flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
     718             : 
     719          28 :     s->ctx_flags |= AVFMTCTX_NOHEADER;
     720             : 
     721          28 :     offset = avio_rb32(s->pb);
     722          28 :     avio_seek(s->pb, offset, SEEK_SET);
     723             : 
     724             :     /* Annex E. The FLV File Format
     725             :      * E.3 TheFLVFileBody
     726             :      *     Field               Type    Comment
     727             :      *     PreviousTagSize0    UI32    Always 0
     728             :      * */
     729          28 :     pre_tag_size = avio_rb32(s->pb);
     730          28 :     if (pre_tag_size) {
     731           0 :         av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
     732             :     }
     733             : 
     734          28 :     s->start_time = 0;
     735          28 :     flv->sum_flv_tag_size = 0;
     736          28 :     flv->last_keyframe_stream_index = -1;
     737             : 
     738          28 :     return 0;
     739             : }
     740             : 
     741          28 : static int flv_read_close(AVFormatContext *s)
     742             : {
     743             :     int i;
     744          28 :     FLVContext *flv = s->priv_data;
     745         112 :     for (i=0; i<FLV_STREAM_TYPE_NB; i++)
     746          84 :         av_freep(&flv->new_extradata[i]);
     747          28 :     av_freep(&flv->keyframe_times);
     748          28 :     av_freep(&flv->keyframe_filepositions);
     749          28 :     return 0;
     750             : }
     751             : 
     752           4 : static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
     753             : {
     754           4 :     av_freep(&st->codecpar->extradata);
     755           4 :     if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
     756           0 :         return AVERROR(ENOMEM);
     757           4 :     st->internal->need_context_update = 1;
     758           4 :     return 0;
     759             : }
     760             : 
     761           2 : static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
     762             :                                int size)
     763             : {
     764           2 :     av_free(flv->new_extradata[stream]);
     765           2 :     flv->new_extradata[stream] = av_mallocz(size +
     766             :                                             AV_INPUT_BUFFER_PADDING_SIZE);
     767           2 :     if (!flv->new_extradata[stream])
     768           0 :         return AVERROR(ENOMEM);
     769           2 :     flv->new_extradata_size[stream] = size;
     770           2 :     avio_read(pb, flv->new_extradata[stream], size);
     771           2 :     return 0;
     772             : }
     773             : 
     774           1 : static void clear_index_entries(AVFormatContext *s, int64_t pos)
     775             : {
     776             :     int i, j, out;
     777           1 :     av_log(s, AV_LOG_WARNING,
     778             :            "Found invalid index entries, clearing the index.\n");
     779           2 :     for (i = 0; i < s->nb_streams; i++) {
     780           1 :         AVStream *st = s->streams[i];
     781             :         /* Remove all index entries that point to >= pos */
     782           1 :         out = 0;
     783         133 :         for (j = 0; j < st->nb_index_entries; j++)
     784         132 :             if (st->index_entries[j].pos < pos)
     785           1 :                 st->index_entries[out++] = st->index_entries[j];
     786           1 :         st->nb_index_entries = out;
     787             :     }
     788           1 : }
     789             : 
     790           0 : static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
     791             : {
     792           0 :     int nb = -1, ret, parse_name = 1;
     793             : 
     794           0 :     switch (type) {
     795           0 :     case AMF_DATA_TYPE_NUMBER:
     796           0 :         avio_skip(pb, 8);
     797           0 :         break;
     798           0 :     case AMF_DATA_TYPE_BOOL:
     799           0 :         avio_skip(pb, 1);
     800           0 :         break;
     801           0 :     case AMF_DATA_TYPE_STRING:
     802           0 :         avio_skip(pb, avio_rb16(pb));
     803           0 :         break;
     804           0 :     case AMF_DATA_TYPE_ARRAY:
     805           0 :         parse_name = 0;
     806           0 :     case AMF_DATA_TYPE_MIXEDARRAY:
     807           0 :         nb = avio_rb32(pb);
     808           0 :     case AMF_DATA_TYPE_OBJECT:
     809           0 :         while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
     810           0 :             if (parse_name) {
     811           0 :                 int size = avio_rb16(pb);
     812           0 :                 if (!size) {
     813           0 :                     avio_skip(pb, 1);
     814           0 :                     break;
     815             :                 }
     816           0 :                 avio_skip(pb, size);
     817             :             }
     818           0 :             if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
     819           0 :                 return ret;
     820             :         }
     821           0 :         break;
     822           0 :     case AMF_DATA_TYPE_NULL:
     823             :     case AMF_DATA_TYPE_OBJECT_END:
     824           0 :         break;
     825           0 :     default:
     826           0 :         return AVERROR_INVALIDDATA;
     827             :     }
     828           0 :     return 0;
     829             : }
     830             : 
     831           0 : static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
     832             :                            int64_t dts, int64_t next)
     833             : {
     834           0 :     AVIOContext *pb = s->pb;
     835           0 :     AVStream *st    = NULL;
     836             :     char buf[20];
     837           0 :     int ret = AVERROR_INVALIDDATA;
     838           0 :     int i, length = -1;
     839           0 :     int array = 0;
     840             : 
     841           0 :     switch (avio_r8(pb)) {
     842           0 :     case AMF_DATA_TYPE_ARRAY:
     843           0 :         array = 1;
     844           0 :     case AMF_DATA_TYPE_MIXEDARRAY:
     845           0 :         avio_seek(pb, 4, SEEK_CUR);
     846           0 :     case AMF_DATA_TYPE_OBJECT:
     847           0 :         break;
     848           0 :     default:
     849           0 :         goto skip;
     850             :     }
     851             : 
     852           0 :     while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
     853           0 :         AMFDataType type = avio_r8(pb);
     854           0 :         if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
     855           0 :             length = avio_rb16(pb);
     856           0 :             ret    = av_get_packet(pb, pkt, length);
     857           0 :             if (ret < 0)
     858           0 :                 goto skip;
     859             :             else
     860           0 :                 break;
     861             :         } else {
     862           0 :             if ((ret = amf_skip_tag(pb, type)) < 0)
     863           0 :                 goto skip;
     864             :         }
     865             :     }
     866             : 
     867           0 :     if (length < 0) {
     868           0 :         ret = AVERROR_INVALIDDATA;
     869           0 :         goto skip;
     870             :     }
     871             : 
     872           0 :     for (i = 0; i < s->nb_streams; i++) {
     873           0 :         st = s->streams[i];
     874           0 :         if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
     875           0 :             break;
     876             :     }
     877             : 
     878           0 :     if (i == s->nb_streams) {
     879           0 :         st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
     880           0 :         if (!st)
     881           0 :             return AVERROR(ENOMEM);
     882           0 :         st->codecpar->codec_id = AV_CODEC_ID_TEXT;
     883             :     }
     884             : 
     885           0 :     pkt->dts  = dts;
     886           0 :     pkt->pts  = dts;
     887           0 :     pkt->size = ret;
     888             : 
     889           0 :     pkt->stream_index = st->index;
     890           0 :     pkt->flags       |= AV_PKT_FLAG_KEY;
     891             : 
     892           0 : skip:
     893           0 :     avio_seek(s->pb, next + 4, SEEK_SET);
     894             : 
     895           0 :     return ret;
     896             : }
     897             : 
     898           0 : static int resync(AVFormatContext *s)
     899             : {
     900           0 :     FLVContext *flv = s->priv_data;
     901             :     int64_t i;
     902           0 :     int64_t pos = avio_tell(s->pb);
     903             : 
     904           0 :     for (i=0; !avio_feof(s->pb); i++) {
     905           0 :         int j  = i & (RESYNC_BUFFER_SIZE-1);
     906           0 :         int j1 = j + RESYNC_BUFFER_SIZE;
     907           0 :         flv->resync_buffer[j ] =
     908           0 :         flv->resync_buffer[j1] = avio_r8(s->pb);
     909             : 
     910           0 :         if (i > 22) {
     911           0 :             unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
     912           0 :             if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
     913           0 :                 unsigned  size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
     914           0 :                 unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
     915           0 :                 if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
     916           0 :                     unsigned  size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
     917           0 :                     if (size1 == lsize1 - 11 && size2  == lsize2 - 11) {
     918           0 :                         avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
     919           0 :                         return 1;
     920             :                     }
     921             :                 }
     922             :             }
     923             :         }
     924             :     }
     925           0 :     return AVERROR_EOF;
     926             : }
     927             : 
     928        4719 : static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
     929             : {
     930        4719 :     FLVContext *flv = s->priv_data;
     931             :     int ret, i, size, flags;
     932             :     enum FlvTagType type;
     933        4719 :     int stream_type=-1;
     934             :     int64_t next, pos, meta_pos;
     935        4719 :     int64_t dts, pts = AV_NOPTS_VALUE;
     936        4719 :     int av_uninit(channels);
     937        4719 :     int av_uninit(sample_rate);
     938        4719 :     AVStream *st    = NULL;
     939        4719 :     int last = -1;
     940             :     int orig_size;
     941             : 
     942        4719 : retry:
     943             :     /* pkt size is repeated at end. skip it */
     944        4719 :         pos  = avio_tell(s->pb);
     945        4719 :         type = (avio_r8(s->pb) & 0x1F);
     946        4719 :         orig_size =
     947        4719 :         size = avio_rb24(s->pb);
     948        4719 :         flv->sum_flv_tag_size += size + 11;
     949        4719 :         dts  = avio_rb24(s->pb);
     950        4719 :         dts |= (unsigned)avio_r8(s->pb) << 24;
     951        4719 :         av_log(s, AV_LOG_TRACE, "type:%d, size:%d, last:%d, dts:%"PRId64" pos:%"PRId64"\n", type, size, last, dts, avio_tell(s->pb));
     952        4719 :         if (avio_feof(s->pb))
     953          56 :             return AVERROR_EOF;
     954        4663 :         avio_skip(s->pb, 3); /* stream id, always 0 */
     955        4663 :         flags = 0;
     956             : 
     957        4663 :         if (flv->validate_next < flv->validate_count) {
     958          11 :             int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
     959          11 :             if (pos == validate_pos) {
     960           3 :                 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
     961             :                     VALIDATE_INDEX_TS_THRESH) {
     962           3 :                     flv->validate_next++;
     963             :                 } else {
     964           0 :                     clear_index_entries(s, validate_pos);
     965           0 :                     flv->validate_count = 0;
     966             :                 }
     967           8 :             } else if (pos > validate_pos) {
     968           1 :                 clear_index_entries(s, validate_pos);
     969           1 :                 flv->validate_count = 0;
     970             :             }
     971             :         }
     972             : 
     973        4663 :         if (size == 0) {
     974           0 :             ret = FFERROR_REDO;
     975           0 :             goto leave;
     976             :         }
     977             : 
     978        4663 :         next = size + avio_tell(s->pb);
     979             : 
     980        4663 :         if (type == FLV_TAG_TYPE_AUDIO) {
     981        2478 :             stream_type = FLV_STREAM_TYPE_AUDIO;
     982        2478 :             flags    = avio_r8(s->pb);
     983        2478 :             size--;
     984        2185 :         } else if (type == FLV_TAG_TYPE_VIDEO) {
     985        2157 :             stream_type = FLV_STREAM_TYPE_VIDEO;
     986        2157 :             flags    = avio_r8(s->pb);
     987        2157 :             size--;
     988        2157 :             if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
     989           0 :                 goto skip;
     990          28 :         } else if (type == FLV_TAG_TYPE_META) {
     991          28 :             stream_type=FLV_STREAM_TYPE_DATA;
     992          28 :             if (size > 13 + 1 + 4) { // Header-type metadata stuff
     993             :                 int type;
     994          28 :                 meta_pos = avio_tell(s->pb);
     995          28 :                 type = flv_read_metabody(s, next);
     996          28 :                 if (type == 0 && dts == 0 || type < 0 || type == TYPE_UNKNOWN) {
     997          28 :                     if (type < 0 && flv->validate_count &&
     998           0 :                         flv->validate_index[0].pos     > next &&
     999           0 :                         flv->validate_index[0].pos - 4 < next
    1000             :                     ) {
    1001           0 :                         av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
    1002           0 :                         next = flv->validate_index[0].pos - 4;
    1003             :                     }
    1004          28 :                     goto skip;
    1005           0 :                 } else if (type == TYPE_ONTEXTDATA) {
    1006           0 :                     avpriv_request_sample(s, "OnTextData packet");
    1007           0 :                     return flv_data_packet(s, pkt, dts, next);
    1008           0 :                 } else if (type == TYPE_ONCAPTION) {
    1009           0 :                     return flv_data_packet(s, pkt, dts, next);
    1010             :                 }
    1011           0 :                 avio_seek(s->pb, meta_pos, SEEK_SET);
    1012             :             }
    1013             :         } else {
    1014           0 :             av_log(s, AV_LOG_DEBUG,
    1015             :                    "Skipping flv packet: type %d, size %d, flags %d.\n",
    1016             :                    type, size, flags);
    1017          28 : skip:
    1018          28 :             if (avio_seek(s->pb, next, SEEK_SET) != next) {
    1019             :                  // This can happen if flv_read_metabody above read past
    1020             :                  // next, on a non-seekable input, and the preceding data has
    1021             :                  // been flushed out from the IO buffer.
    1022           0 :                  av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
    1023           0 :                  return AVERROR_INVALIDDATA;
    1024             :             }
    1025          28 :             ret = FFERROR_REDO;
    1026          28 :             goto leave;
    1027             :         }
    1028             : 
    1029             :         /* skip empty data packets */
    1030        4635 :         if (!size) {
    1031           0 :             ret = FFERROR_REDO;
    1032           0 :             goto leave;
    1033             :         }
    1034             : 
    1035             :         /* now find stream */
    1036        5844 :         for (i = 0; i < s->nb_streams; i++) {
    1037        5814 :             st = s->streams[i];
    1038        5814 :             if (stream_type == FLV_STREAM_TYPE_AUDIO) {
    1039        6149 :                 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
    1040        4940 :                     (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
    1041             :                     break;
    1042        2135 :             } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
    1043        4270 :                 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
    1044        4270 :                     (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
    1045             :                     break;
    1046           0 :             } else if (stream_type == FLV_STREAM_TYPE_DATA) {
    1047           0 :                 if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
    1048           0 :                     break;
    1049             :             }
    1050             :         }
    1051        4635 :         if (i == s->nb_streams) {
    1052             :             static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE};
    1053          30 :             st = create_stream(s, stream_types[stream_type]);
    1054          30 :             if (!st)
    1055           0 :                 return AVERROR(ENOMEM);
    1056             : 
    1057             :         }
    1058        4635 :         av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
    1059             : 
    1060        9270 :         if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
    1061        8281 :             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
    1062             :               stream_type == FLV_STREAM_TYPE_AUDIO))
    1063        2941 :             av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
    1064             : 
    1065        4635 :         if (  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
    1066        4357 :             ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
    1067        4357 :             || st->discard >= AVDISCARD_ALL
    1068             :         ) {
    1069         288 :             avio_seek(s->pb, next, SEEK_SET);
    1070         288 :             ret = FFERROR_REDO;
    1071         288 :             goto leave;
    1072             :         }
    1073             : 
    1074             :     // if not streamed and no duration from metadata then seek to end to find
    1075             :     // the duration from the timestamps
    1076        8694 :     if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
    1077        8694 :         (!s->duration || s->duration == AV_NOPTS_VALUE) &&
    1078           0 :         !flv->searched_for_end) {
    1079             :         int size;
    1080           0 :         const int64_t pos   = avio_tell(s->pb);
    1081             :         // Read the last 4 bytes of the file, this should be the size of the
    1082             :         // previous FLV tag. Use the timestamp of its payload as duration.
    1083           0 :         int64_t fsize       = avio_size(s->pb);
    1084           0 : retry_duration:
    1085           0 :         avio_seek(s->pb, fsize - 4, SEEK_SET);
    1086           0 :         size = avio_rb32(s->pb);
    1087           0 :         if (size > 0 && size < fsize) {
    1088             :             // Seek to the start of the last FLV tag at position (fsize - 4 - size)
    1089             :             // but skip the byte indicating the type.
    1090           0 :             avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
    1091           0 :             if (size == avio_rb24(s->pb) + 11) {
    1092           0 :                 uint32_t ts = avio_rb24(s->pb);
    1093           0 :                 ts         |= avio_r8(s->pb) << 24;
    1094           0 :                 if (ts)
    1095           0 :                     s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
    1096           0 :                 else if (fsize >= 8 && fsize - 8 >= size) {
    1097           0 :                     fsize -= size+4;
    1098           0 :                     goto retry_duration;
    1099             :                 }
    1100             :             }
    1101             :         }
    1102             : 
    1103           0 :         avio_seek(s->pb, pos, SEEK_SET);
    1104           0 :         flv->searched_for_end = 1;
    1105             :     }
    1106             : 
    1107        4347 :     if (stream_type == FLV_STREAM_TYPE_AUDIO) {
    1108             :         int bits_per_coded_sample;
    1109        2478 :         channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
    1110        2478 :         sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
    1111             :                                 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
    1112        2478 :         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
    1113        4948 :         if (!st->codecpar->channels || !st->codecpar->sample_rate ||
    1114        2470 :             !st->codecpar->bits_per_coded_sample) {
    1115           8 :             st->codecpar->channels              = channels;
    1116           8 :             st->codecpar->channel_layout        = channels == 1
    1117             :                                                ? AV_CH_LAYOUT_MONO
    1118           8 :                                                : AV_CH_LAYOUT_STEREO;
    1119           8 :             st->codecpar->sample_rate           = sample_rate;
    1120           8 :             st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
    1121             :         }
    1122        2478 :         if (!st->codecpar->codec_id) {
    1123           8 :             flv_set_audio_codec(s, st, st->codecpar,
    1124             :                                 flags & FLV_AUDIO_CODECID_MASK);
    1125           8 :             flv->last_sample_rate =
    1126           8 :             sample_rate           = st->codecpar->sample_rate;
    1127           8 :             flv->last_channels    =
    1128           8 :             channels              = st->codecpar->channels;
    1129             :         } else {
    1130        2470 :             AVCodecParameters *par = avcodec_parameters_alloc();
    1131        2470 :             if (!par) {
    1132           0 :                 ret = AVERROR(ENOMEM);
    1133           0 :                 goto leave;
    1134             :             }
    1135        2470 :             par->sample_rate = sample_rate;
    1136        2470 :             par->bits_per_coded_sample = bits_per_coded_sample;
    1137        2470 :             flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
    1138        2470 :             sample_rate = par->sample_rate;
    1139        2470 :             avcodec_parameters_free(&par);
    1140             :         }
    1141        1869 :     } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
    1142        1869 :         int ret = flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
    1143        1869 :         if (ret < 0)
    1144           0 :             return ret;
    1145        1869 :         size -= ret;
    1146           0 :     } else if (stream_type == FLV_STREAM_TYPE_DATA) {
    1147           0 :         st->codecpar->codec_id = AV_CODEC_ID_TEXT;
    1148             :     }
    1149             : 
    1150        8440 :     if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
    1151        7528 :         st->codecpar->codec_id == AV_CODEC_ID_H264 ||
    1152        3435 :         st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
    1153         912 :         int type = avio_r8(s->pb);
    1154         912 :         size--;
    1155             : 
    1156         912 :         if (size < 0) {
    1157           0 :             ret = AVERROR_INVALIDDATA;
    1158           0 :             goto leave;
    1159             :         }
    1160             : 
    1161         912 :         if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
    1162             :             // sign extension
    1163         658 :             int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
    1164         658 :             pts = dts + cts;
    1165         658 :             if (cts < 0) { // dts might be wrong
    1166           0 :                 if (!flv->wrong_dts)
    1167           0 :                     av_log(s, AV_LOG_WARNING,
    1168             :                         "Negative cts, previous timestamps might be wrong.\n");
    1169           0 :                 flv->wrong_dts = 1;
    1170         658 :             } else if (FFABS(dts - pts) > 1000*60*15) {
    1171           0 :                 av_log(s, AV_LOG_WARNING,
    1172             :                        "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
    1173           0 :                 dts = pts = AV_NOPTS_VALUE;
    1174             :             }
    1175             :         }
    1176         913 :         if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
    1177           1 :             st->codecpar->codec_id == AV_CODEC_ID_H264)) {
    1178             :             AVDictionaryEntry *t;
    1179             : 
    1180           6 :             if (st->codecpar->extradata) {
    1181           2 :                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
    1182           0 :                     return ret;
    1183           2 :                 ret = FFERROR_REDO;
    1184           2 :                 goto leave;
    1185             :             }
    1186           4 :             if ((ret = flv_get_extradata(s, st, size)) < 0)
    1187           0 :                 return ret;
    1188             : 
    1189             :             /* Workaround for buggy Omnia A/XE encoder */
    1190           4 :             t = av_dict_get(s->metadata, "Encoder", NULL, 0);
    1191           4 :             if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
    1192           0 :                 st->codecpar->extradata_size = 2;
    1193             : 
    1194             :             if (st->codecpar->codec_id == AV_CODEC_ID_AAC && 0) {
    1195             :                 MPEG4AudioConfig cfg;
    1196             : 
    1197             :                 if (avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
    1198             :                                                  st->codecpar->extradata_size * 8, 1) >= 0) {
    1199             :                 st->codecpar->channels       = cfg.channels;
    1200             :                 st->codecpar->channel_layout = 0;
    1201             :                 if (cfg.ext_sample_rate)
    1202             :                     st->codecpar->sample_rate = cfg.ext_sample_rate;
    1203             :                 else
    1204             :                     st->codecpar->sample_rate = cfg.sample_rate;
    1205             :                 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
    1206             :                         st->codecpar->channels, st->codecpar->sample_rate);
    1207             :                 }
    1208             :             }
    1209             : 
    1210           4 :             ret = FFERROR_REDO;
    1211           4 :             goto leave;
    1212             :         }
    1213             :     }
    1214             : 
    1215             :     /* skip empty data packets */
    1216        4341 :     if (!size) {
    1217           1 :         ret = FFERROR_REDO;
    1218           1 :         goto leave;
    1219             :     }
    1220             : 
    1221        4340 :     ret = av_get_packet(s->pb, pkt, size);
    1222        4340 :     if (ret < 0)
    1223           0 :         return ret;
    1224        4340 :     pkt->dts          = dts;
    1225        4340 :     pkt->pts          = pts == AV_NOPTS_VALUE ? dts : pts;
    1226        4340 :     pkt->stream_index = st->index;
    1227        4340 :     pkt->pos          = pos;
    1228        4340 :     if (flv->new_extradata[stream_type]) {
    1229           2 :         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
    1230             :                                                 flv->new_extradata_size[stream_type]);
    1231           2 :         if (side) {
    1232           2 :             memcpy(side, flv->new_extradata[stream_type],
    1233           2 :                    flv->new_extradata_size[stream_type]);
    1234           2 :             av_freep(&flv->new_extradata[stream_type]);
    1235           2 :             flv->new_extradata_size[stream_type] = 0;
    1236             :         }
    1237             :     }
    1238        6816 :     if (stream_type == FLV_STREAM_TYPE_AUDIO &&
    1239        4952 :                     (sample_rate != flv->last_sample_rate ||
    1240        2476 :                      channels    != flv->last_channels)) {
    1241           0 :         flv->last_sample_rate = sample_rate;
    1242           0 :         flv->last_channels    = channels;
    1243           0 :         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
    1244             :     }
    1245             : 
    1246        6204 :     if (    stream_type == FLV_STREAM_TYPE_AUDIO ||
    1247        3280 :             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
    1248             :             stream_type == FLV_STREAM_TYPE_DATA)
    1249        2924 :         pkt->flags |= AV_PKT_FLAG_KEY;
    1250             : 
    1251        6079 : leave:
    1252        4663 :     last = avio_rb32(s->pb);
    1253        4664 :     if (last != orig_size + 11 && last != orig_size + 10 &&
    1254           1 :         !avio_feof(s->pb) &&
    1255           0 :         (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
    1256           0 :         !flv->broken_sizes) {
    1257           0 :         av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
    1258           0 :         avio_seek(s->pb, pos + 1, SEEK_SET);
    1259           0 :         ret = resync(s);
    1260           0 :         av_packet_unref(pkt);
    1261           0 :         if (ret >= 0) {
    1262           0 :             goto retry;
    1263             :         }
    1264             :     }
    1265        4663 :     return ret;
    1266             : }
    1267             : 
    1268         285 : static int flv_read_seek(AVFormatContext *s, int stream_index,
    1269             :                          int64_t ts, int flags)
    1270             : {
    1271         285 :     FLVContext *flv = s->priv_data;
    1272         285 :     flv->validate_count = 0;
    1273         285 :     return avio_seek_time(s->pb, stream_index, ts, flags);
    1274             : }
    1275             : 
    1276             : #define OFFSET(x) offsetof(FLVContext, x)
    1277             : #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
    1278             : static const AVOption options[] = {
    1279             :     { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
    1280             :     { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
    1281             :     { NULL }
    1282             : };
    1283             : 
    1284             : static const AVClass flv_class = {
    1285             :     .class_name = "flvdec",
    1286             :     .item_name  = av_default_item_name,
    1287             :     .option     = options,
    1288             :     .version    = LIBAVUTIL_VERSION_INT,
    1289             : };
    1290             : 
    1291             : AVInputFormat ff_flv_demuxer = {
    1292             :     .name           = "flv",
    1293             :     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
    1294             :     .priv_data_size = sizeof(FLVContext),
    1295             :     .read_probe     = flv_probe,
    1296             :     .read_header    = flv_read_header,
    1297             :     .read_packet    = flv_read_packet,
    1298             :     .read_seek      = flv_read_seek,
    1299             :     .read_close     = flv_read_close,
    1300             :     .extensions     = "flv",
    1301             :     .priv_class     = &flv_class,
    1302             : };
    1303             : 
    1304             : static const AVClass live_flv_class = {
    1305             :     .class_name = "live_flvdec",
    1306             :     .item_name  = av_default_item_name,
    1307             :     .option     = options,
    1308             :     .version    = LIBAVUTIL_VERSION_INT,
    1309             : };
    1310             : 
    1311             : AVInputFormat ff_live_flv_demuxer = {
    1312             :     .name           = "live_flv",
    1313             :     .long_name      = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
    1314             :     .priv_data_size = sizeof(FLVContext),
    1315             :     .read_probe     = live_flv_probe,
    1316             :     .read_header    = flv_read_header,
    1317             :     .read_packet    = flv_read_packet,
    1318             :     .read_seek      = flv_read_seek,
    1319             :     .read_close     = flv_read_close,
    1320             :     .extensions     = "flv",
    1321             :     .priv_class     = &live_flv_class,
    1322             :     .flags          = AVFMT_TS_DISCONT
    1323             : };

Generated by: LCOV version 1.13