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