]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
crypto: consistently use size_t as type for length parameters
[ffmpeg] / libavformat / flvdec.c
1 /*
2  * FLV demuxer
3  * Copyright (c) 2003 The Libav 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 Libav.
11  *
12  * Libav 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  * Libav 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 Libav; 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 KEYFRAMES_TAG            "keyframes"
41 #define KEYFRAMES_TIMESTAMP_TAG  "times"
42 #define KEYFRAMES_BYTEOFFSET_TAG "filepositions"
43
44 #define VALIDATE_INDEX_TS_THRESH 2500
45
46 typedef struct FLVContext {
47     const AVClass *class; ///< Class for private options.
48     int trust_metadata;   ///< configure streams according onMetaData
49     int wrong_dts;        ///< wrong dts due to negative cts
50     uint8_t *new_extradata[2];
51     int new_extradata_size[2];
52     int last_sample_rate;
53     int last_channels;
54     struct {
55         int64_t dts;
56         int64_t pos;
57     } validate_index[2];
58     int validate_next;
59     int validate_count;
60     int searched_for_end;
61 } FLVContext;
62
63 static int flv_probe(AVProbeData *p)
64 {
65     const uint8_t *d;
66
67     d = p->buf;
68     if (d[0] == 'F' &&
69         d[1] == 'L' &&
70         d[2] == 'V' &&
71         d[3] < 5 && d[5] == 0 &&
72         AV_RB32(d + 5) > 8) {
73         return AVPROBE_SCORE_MAX;
74     }
75     return 0;
76 }
77
78 static AVStream *create_stream(AVFormatContext *s, int codec_type)
79 {
80     AVStream *st = avformat_new_stream(s, NULL);
81     if (!st)
82         return NULL;
83     st->codecpar->codec_type = codec_type;
84     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
85     return st;
86 }
87
88 static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
89 {
90     int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
91     int flv_codecid           = flags & FLV_AUDIO_CODECID_MASK;
92     int codec_id;
93
94     if (!apar->codec_id && !apar->codec_tag)
95         return 1;
96
97     if (apar->bits_per_coded_sample != bits_per_coded_sample)
98         return 0;
99
100     switch (flv_codecid) {
101     // no distinction between S16 and S8 PCM codec flags
102     case FLV_CODECID_PCM:
103         codec_id = bits_per_coded_sample == 8
104                    ? AV_CODEC_ID_PCM_U8
105 #if HAVE_BIGENDIAN
106                    : AV_CODEC_ID_PCM_S16BE;
107 #else
108                    : AV_CODEC_ID_PCM_S16LE;
109 #endif
110         return codec_id == apar->codec_id;
111     case FLV_CODECID_PCM_LE:
112         codec_id = bits_per_coded_sample == 8
113                    ? AV_CODEC_ID_PCM_U8
114                    : AV_CODEC_ID_PCM_S16LE;
115         return codec_id == apar->codec_id;
116     case FLV_CODECID_AAC:
117         return apar->codec_id == AV_CODEC_ID_AAC;
118     case FLV_CODECID_ADPCM:
119         return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
120     case FLV_CODECID_SPEEX:
121         return apar->codec_id == AV_CODEC_ID_SPEEX;
122     case FLV_CODECID_MP3:
123         return apar->codec_id == AV_CODEC_ID_MP3;
124     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
125     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
126     case FLV_CODECID_NELLYMOSER:
127         return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
128     case FLV_CODECID_PCM_MULAW:
129         return apar->sample_rate == 8000 &&
130                apar->codec_id    == AV_CODEC_ID_PCM_MULAW;
131     case FLV_CODECID_PCM_ALAW:
132         return apar->sample_rate == 8000 &&
133                apar->codec_id    == AV_CODEC_ID_PCM_ALAW;
134     default:
135         return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
136     }
137 }
138
139 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
140                                 AVCodecParameters *apar, int flv_codecid)
141 {
142     switch (flv_codecid) {
143     // no distinction between S16 and S8 PCM codec flags
144     case FLV_CODECID_PCM:
145         apar->codec_id = apar->bits_per_coded_sample == 8
146                            ? AV_CODEC_ID_PCM_U8
147 #if HAVE_BIGENDIAN
148                            : AV_CODEC_ID_PCM_S16BE;
149 #else
150                            : AV_CODEC_ID_PCM_S16LE;
151 #endif
152         break;
153     case FLV_CODECID_PCM_LE:
154         apar->codec_id = apar->bits_per_coded_sample == 8
155                            ? AV_CODEC_ID_PCM_U8
156                            : AV_CODEC_ID_PCM_S16LE;
157         break;
158     case FLV_CODECID_AAC:
159         apar->codec_id = AV_CODEC_ID_AAC;
160         break;
161     case FLV_CODECID_ADPCM:
162         apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
163         break;
164     case FLV_CODECID_SPEEX:
165         apar->codec_id    = AV_CODEC_ID_SPEEX;
166         apar->sample_rate = 16000;
167         break;
168     case FLV_CODECID_MP3:
169         apar->codec_id      = AV_CODEC_ID_MP3;
170         astream->need_parsing = AVSTREAM_PARSE_FULL;
171         break;
172     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
173         // in case metadata does not otherwise declare samplerate
174         apar->sample_rate = 8000;
175         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
176         break;
177     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
178         apar->sample_rate = 16000;
179         apar->codec_id    = AV_CODEC_ID_NELLYMOSER;
180         break;
181     case FLV_CODECID_NELLYMOSER:
182         apar->codec_id = AV_CODEC_ID_NELLYMOSER;
183         break;
184     case FLV_CODECID_PCM_MULAW:
185         apar->sample_rate = 8000;
186         apar->codec_id    = AV_CODEC_ID_PCM_MULAW;
187         break;
188     case FLV_CODECID_PCM_ALAW:
189         apar->sample_rate = 8000;
190         apar->codec_id    = AV_CODEC_ID_PCM_ALAW;
191         break;
192     default:
193         av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n",
194                flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
195         apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
196     }
197 }
198
199 static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
200 {
201     int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
202
203     if (!vpar->codec_id && !vpar->codec_tag)
204         return 1;
205
206     switch (flv_codecid) {
207     case FLV_CODECID_H263:
208         return vpar->codec_id == AV_CODEC_ID_FLV1;
209     case FLV_CODECID_SCREEN:
210         return vpar->codec_id == AV_CODEC_ID_FLASHSV;
211     case FLV_CODECID_SCREEN2:
212         return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
213     case FLV_CODECID_VP6:
214         return vpar->codec_id == AV_CODEC_ID_VP6F;
215     case FLV_CODECID_VP6A:
216         return vpar->codec_id == AV_CODEC_ID_VP6A;
217     case FLV_CODECID_H264:
218         return vpar->codec_id == AV_CODEC_ID_H264;
219     default:
220         return vpar->codec_tag == flv_codecid;
221     }
222 }
223
224 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
225                                int flv_codecid, int read)
226 {
227     AVCodecParameters *par = vstream->codecpar;
228     switch (flv_codecid) {
229     case FLV_CODECID_H263:
230         par->codec_id = AV_CODEC_ID_FLV1;
231         break;
232     case FLV_CODECID_SCREEN:
233         par->codec_id = AV_CODEC_ID_FLASHSV;
234         break;
235     case FLV_CODECID_SCREEN2:
236         par->codec_id = AV_CODEC_ID_FLASHSV2;
237         break;
238     case FLV_CODECID_VP6:
239         par->codec_id = AV_CODEC_ID_VP6F;
240     case FLV_CODECID_VP6A:
241         if (flv_codecid == FLV_CODECID_VP6A)
242             par->codec_id = AV_CODEC_ID_VP6A;
243         if (read) {
244             if (par->extradata_size != 1) {
245                 par->extradata = av_malloc(1);
246                 if (par->extradata)
247                     par->extradata_size = 1;
248             }
249             if (par->extradata)
250                 par->extradata[0] = avio_r8(s->pb);
251             else
252                 avio_skip(s->pb, 1);
253         }
254         return 1;     // 1 byte body size adjustment for flv_read_packet()
255     case FLV_CODECID_H264:
256         par->codec_id = AV_CODEC_ID_H264;
257         return 3;     // not 4, reading packet type will consume one byte
258     default:
259         av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
260         par->codec_tag = flv_codecid;
261     }
262
263     return 0;
264 }
265
266 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
267 {
268     int length = avio_rb16(ioc);
269     if (length >= buffsize) {
270         avio_skip(ioc, length);
271         return -1;
272     }
273
274     avio_read(ioc, buffer, length);
275
276     buffer[length] = '\0';
277
278     return length;
279 }
280
281 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc,
282                                  AVStream *vstream, int64_t max_pos)
283 {
284     FLVContext *flv       = s->priv_data;
285     unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
286     double num_val;
287     char str_val[256];
288     int64_t *times         = NULL;
289     int64_t *filepositions = NULL;
290     int ret                = AVERROR(ENOSYS);
291     int64_t initial_pos    = avio_tell(ioc);
292
293     if (s->flags & AVFMT_FLAG_IGNIDX)
294         return 0;
295
296     while (avio_tell(ioc) < max_pos - 2 &&
297            amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
298         int64_t *current_array;
299
300         // Expect array object in context
301         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
302             break;
303
304         arraylen = avio_rb32(ioc);
305         if (arraylen >> 28)
306             break;
307
308         /* Expect only 'times' or 'filepositions' sub-arrays in other
309          * case refuse to use such metadata for indexing. */
310         if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
311             if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
312                 ret = AVERROR(ENOMEM);
313                 goto finish;
314             }
315             timeslen      = arraylen;
316             current_array = times;
317         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
318                    !filepositions) {
319             if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
320                 ret = AVERROR(ENOMEM);
321                 goto finish;
322             }
323             fileposlen    = arraylen;
324             current_array = filepositions;
325         } else
326             // unexpected metatag inside keyframes, will not use such
327             // metadata for indexing
328             break;
329
330         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
331             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
332                 goto finish;
333             num_val          = av_int2double(avio_rb64(ioc));
334             current_array[i] = num_val;
335         }
336         if (times && filepositions) {
337             // All done, exiting at a position allowing amf_parse_object
338             // to finish parsing the object
339             ret = 0;
340             break;
341         }
342     }
343
344     if (!ret && timeslen == fileposlen) {
345         for (i = 0; i < fileposlen; i++) {
346             av_add_index_entry(vstream, filepositions[i], times[i] * 1000,
347                                0, 0, AVINDEX_KEYFRAME);
348             if (i < 2) {
349                 flv->validate_index[i].pos = filepositions[i];
350                 flv->validate_index[i].dts = times[i] * 1000;
351                 flv->validate_count        = i + 1;
352             }
353         }
354     } else
355         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
356
357 finish:
358     av_freep(&times);
359     av_freep(&filepositions);
360     // If we got unexpected data, but successfully reset back to
361     // the start pos, the caller can continue parsing
362     if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
363         return 0;
364     return ret;
365 }
366
367 static int amf_parse_object(AVFormatContext *s, AVStream *astream,
368                             AVStream *vstream, const char *key,
369                             int64_t max_pos, int depth)
370 {
371     AVCodecParameters *apar, *vpar;
372     FLVContext *flv = s->priv_data;
373     AVIOContext *ioc;
374     AMFDataType amf_type;
375     char str_val[256];
376     double num_val;
377
378     num_val  = 0;
379     ioc      = s->pb;
380     amf_type = avio_r8(ioc);
381
382     switch (amf_type) {
383     case AMF_DATA_TYPE_NUMBER:
384         num_val = av_int2double(avio_rb64(ioc));
385         break;
386     case AMF_DATA_TYPE_BOOL:
387         num_val = avio_r8(ioc);
388         break;
389     case AMF_DATA_TYPE_STRING:
390         if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
391             return -1;
392         break;
393     case AMF_DATA_TYPE_OBJECT:
394         if ((vstream || astream) && key &&
395             !strcmp(KEYFRAMES_TAG, key) && depth == 1)
396             if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
397                                       max_pos) < 0)
398                 return -1;
399
400         while (avio_tell(ioc) < max_pos - 2 &&
401                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
402             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
403                                  depth + 1) < 0)
404                 return -1;     // if we couldn't skip, bomb out.
405         if (avio_r8(ioc) != AMF_END_OF_OBJECT)
406             return -1;
407         break;
408     case AMF_DATA_TYPE_NULL:
409     case AMF_DATA_TYPE_UNDEFINED:
410     case AMF_DATA_TYPE_UNSUPPORTED:
411         break;     // these take up no additional space
412     case AMF_DATA_TYPE_MIXEDARRAY:
413         avio_skip(ioc, 4);     // skip 32-bit max array index
414         while (avio_tell(ioc) < max_pos - 2 &&
415                amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
416             // this is the only case in which we would want a nested
417             // parse to not skip over the object
418             if (amf_parse_object(s, astream, vstream, str_val, max_pos,
419                                  depth + 1) < 0)
420                 return -1;
421         if (avio_r8(ioc) != AMF_END_OF_OBJECT)
422             return -1;
423         break;
424     case AMF_DATA_TYPE_ARRAY:
425     {
426         unsigned int arraylen, i;
427
428         arraylen = avio_rb32(ioc);
429         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
430             if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
431                                  depth + 1) < 0)
432                 return -1;      // if we couldn't skip, bomb out.
433     }
434     break;
435     case AMF_DATA_TYPE_DATE:
436         avio_skip(ioc, 8 + 2);  // timestamp (double) and UTC offset (int16)
437         break;
438     default:                    // unsupported type, we couldn't skip
439         return -1;
440     }
441
442     if (key) {
443         // stream info doesn't live any deeper than the first object
444         if (depth == 1) {
445             apar = astream ? astream->codecpar : NULL;
446             vpar = vstream ? vstream->codecpar : NULL;
447
448             if (amf_type == AMF_DATA_TYPE_NUMBER ||
449                 amf_type == AMF_DATA_TYPE_BOOL) {
450                 if (!strcmp(key, "duration"))
451                     s->duration = num_val * AV_TIME_BASE;
452                 else if (!strcmp(key, "videodatarate") && vpar &&
453                          0 <= (int)(num_val * 1024.0))
454                     vpar->bit_rate = num_val * 1024.0;
455                 else if (!strcmp(key, "audiodatarate") && apar &&
456                          0 <= (int)(num_val * 1024.0))
457                     apar->bit_rate = num_val * 1024.0;
458                 else if (!strcmp(key, "datastream")) {
459                     AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);
460                     if (!st)
461                         return AVERROR(ENOMEM);
462                     st->codecpar->codec_id = AV_CODEC_ID_TEXT;
463                 } else if (flv->trust_metadata) {
464                     if (!strcmp(key, "videocodecid") && vpar) {
465                         flv_set_video_codec(s, vstream, num_val, 0);
466                     } else if (!strcmp(key, "audiocodecid") && apar) {
467                         int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
468                         flv_set_audio_codec(s, astream, apar, id);
469                     } else if (!strcmp(key, "audiosamplerate") && apar) {
470                         apar->sample_rate = num_val;
471                     } else if (!strcmp(key, "audiosamplesize") && apar) {
472                         apar->bits_per_coded_sample = num_val;
473                     } else if (!strcmp(key, "stereo") && apar) {
474                         apar->channels       = num_val + 1;
475                         apar->channel_layout = apar->channels == 2 ?
476                                                AV_CH_LAYOUT_STEREO :
477                                                AV_CH_LAYOUT_MONO;
478                     } else if (!strcmp(key, "width") && vpar) {
479                         vpar->width = num_val;
480                     } else if (!strcmp(key, "height") && vpar) {
481                         vpar->height = num_val;
482                     }
483                 }
484             }
485         }
486
487         if (!strcmp(key, "duration")        ||
488             !strcmp(key, "filesize")        ||
489             !strcmp(key, "width")           ||
490             !strcmp(key, "height")          ||
491             !strcmp(key, "videodatarate")   ||
492             !strcmp(key, "framerate")       ||
493             !strcmp(key, "videocodecid")    ||
494             !strcmp(key, "audiodatarate")   ||
495             !strcmp(key, "audiosamplerate") ||
496             !strcmp(key, "audiosamplesize") ||
497             !strcmp(key, "stereo")          ||
498             !strcmp(key, "audiocodecid")    ||
499             !strcmp(key, "datastream"))
500             return 0;
501
502         s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
503         if (amf_type == AMF_DATA_TYPE_BOOL) {
504             av_strlcpy(str_val, num_val > 0 ? "true" : "false",
505                        sizeof(str_val));
506             av_dict_set(&s->metadata, key, str_val, 0);
507         } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
508             snprintf(str_val, sizeof(str_val), "%.f", num_val);
509             av_dict_set(&s->metadata, key, str_val, 0);
510         } else if (amf_type == AMF_DATA_TYPE_STRING)
511             av_dict_set(&s->metadata, key, str_val, 0);
512     }
513
514     return 0;
515 }
516
517 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
518 {
519     AMFDataType type;
520     AVStream *stream, *astream, *vstream;
521     AVIOContext *ioc;
522     int i;
523     // only needs to hold the string "onMetaData".
524     // Anything longer is something we don't want.
525     char buffer[11];
526
527     astream = NULL;
528     vstream = NULL;
529     ioc     = s->pb;
530
531     // first object needs to be "onMetaData" string
532     type = avio_r8(ioc);
533     if (type != AMF_DATA_TYPE_STRING ||
534         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
535         return -1;
536
537     if (!strcmp(buffer, "onTextData"))
538         return 1;
539
540     if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint"))
541         return -1;
542
543     // find the streams now so that amf_parse_object doesn't need to do
544     // the lookup every time it is called.
545     for (i = 0; i < s->nb_streams; i++) {
546         stream = s->streams[i];
547         if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)
548             astream = stream;
549         else if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
550             vstream = stream;
551     }
552
553     // parse the second object (we want a mixed array)
554     if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
555         return -1;
556
557     return 0;
558 }
559
560 static int flv_read_header(AVFormatContext *s)
561 {
562     int offset;
563
564     avio_skip(s->pb, 4);
565     avio_r8(s->pb); // flags
566
567     s->ctx_flags |= AVFMTCTX_NOHEADER;
568
569     offset = avio_rb32(s->pb);
570     avio_seek(s->pb, offset, SEEK_SET);
571     avio_skip(s->pb, 4);
572
573     s->start_time = 0;
574
575     return 0;
576 }
577
578 static int flv_read_close(AVFormatContext *s)
579 {
580     FLVContext *flv = s->priv_data;
581     av_freep(&flv->new_extradata[0]);
582     av_freep(&flv->new_extradata[1]);
583     return 0;
584 }
585
586 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
587 {
588     av_free(st->codecpar->extradata);
589     st->codecpar->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);
590     if (!st->codecpar->extradata)
591         return AVERROR(ENOMEM);
592     st->codecpar->extradata_size = size;
593     avio_read(s->pb, st->codecpar->extradata, st->codecpar->extradata_size);
594     return 0;
595 }
596
597 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
598                                int size)
599 {
600     av_free(flv->new_extradata[stream]);
601     flv->new_extradata[stream] = av_mallocz(size +
602                                             AV_INPUT_BUFFER_PADDING_SIZE);
603     if (!flv->new_extradata[stream])
604         return AVERROR(ENOMEM);
605     flv->new_extradata_size[stream] = size;
606     avio_read(pb, flv->new_extradata[stream], size);
607     return 0;
608 }
609
610 static void clear_index_entries(AVFormatContext *s, int64_t pos)
611 {
612     int i, j, out;
613     av_log(s, AV_LOG_WARNING,
614            "Found invalid index entries, clearing the index.\n");
615     for (i = 0; i < s->nb_streams; i++) {
616         AVStream *st = s->streams[i];
617         /* Remove all index entries that point to >= pos */
618         out = 0;
619         for (j = 0; j < st->nb_index_entries; j++)
620             if (st->index_entries[j].pos < pos)
621                 st->index_entries[out++] = st->index_entries[j];
622         st->nb_index_entries = out;
623     }
624 }
625
626 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
627 {
628     int nb = -1, ret, parse_name = 1;
629
630     switch (type) {
631     case AMF_DATA_TYPE_NUMBER:
632         avio_skip(pb, 8);
633         break;
634     case AMF_DATA_TYPE_BOOL:
635         avio_skip(pb, 1);
636         break;
637     case AMF_DATA_TYPE_STRING:
638         avio_skip(pb, avio_rb16(pb));
639         break;
640     case AMF_DATA_TYPE_ARRAY:
641         parse_name = 0;
642     case AMF_DATA_TYPE_MIXEDARRAY:
643         nb = avio_rb32(pb);
644     case AMF_DATA_TYPE_OBJECT:
645         while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
646             if (parse_name) {
647                 int size = avio_rb16(pb);
648                 if (!size) {
649                     avio_skip(pb, 1);
650                     break;
651                 }
652                 avio_skip(pb, size);
653             }
654             if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
655                 return ret;
656         }
657         break;
658     case AMF_DATA_TYPE_NULL:
659     case AMF_DATA_TYPE_OBJECT_END:
660         break;
661     default:
662         return AVERROR_INVALIDDATA;
663     }
664     return 0;
665 }
666
667 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
668                            int64_t dts, int64_t next)
669 {
670     AVIOContext *pb = s->pb;
671     AVStream *st    = NULL;
672     char buf[20];
673     int ret = AVERROR_INVALIDDATA;
674     int i, length = -1;
675
676     switch (avio_r8(pb)) {
677     case AMF_DATA_TYPE_MIXEDARRAY:
678         avio_seek(pb, 4, SEEK_CUR);
679     case AMF_DATA_TYPE_OBJECT:
680         break;
681     default:
682         goto skip;
683     }
684
685     while ((ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
686         AMFDataType type = avio_r8(pb);
687         if (type == AMF_DATA_TYPE_STRING && !strcmp(buf, "text")) {
688             length = avio_rb16(pb);
689             ret    = av_get_packet(pb, pkt, length);
690             if (ret < 0)
691                 goto skip;
692             else
693                 break;
694         } else {
695             if ((ret = amf_skip_tag(pb, type)) < 0)
696                 goto skip;
697         }
698     }
699
700     if (length < 0) {
701         ret = AVERROR_INVALIDDATA;
702         goto skip;
703     }
704
705     for (i = 0; i < s->nb_streams; i++) {
706         st = s->streams[i];
707         if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
708             break;
709     }
710
711     if (i == s->nb_streams) {
712         st = create_stream(s, AVMEDIA_TYPE_DATA);
713         if (!st)
714             return AVERROR(ENOMEM);
715         st->codecpar->codec_id = AV_CODEC_ID_TEXT;
716     }
717
718     pkt->dts  = dts;
719     pkt->pts  = dts;
720     pkt->size = ret;
721
722     pkt->stream_index = st->index;
723     pkt->flags       |= AV_PKT_FLAG_KEY;
724
725 skip:
726     avio_seek(s->pb, next + 4, SEEK_SET);
727
728     return ret;
729 }
730
731 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
732 {
733     FLVContext *flv = s->priv_data;
734     int ret, i, size, flags, is_audio;
735     enum FlvTagType type;
736     int64_t next, pos;
737     int64_t dts, pts = AV_NOPTS_VALUE;
738     int sample_rate = 0, channels = 0;
739     AVStream *st    = NULL;
740
741     /* pkt size is repeated at end. skip it */
742     for (;; avio_skip(s->pb, 4)) {
743         pos  = avio_tell(s->pb);
744         type = avio_r8(s->pb);
745         size = avio_rb24(s->pb);
746         dts  = avio_rb24(s->pb);
747         dts |= avio_r8(s->pb) << 24;
748         av_log(s, AV_LOG_TRACE, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
749         if (s->pb->eof_reached)
750             return AVERROR_EOF;
751         avio_skip(s->pb, 3); /* stream id, always 0 */
752         flags = 0;
753
754         if (flv->validate_next < flv->validate_count) {
755             int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
756             if (pos == validate_pos) {
757                 if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
758                     VALIDATE_INDEX_TS_THRESH) {
759                     flv->validate_next++;
760                 } else {
761                     clear_index_entries(s, validate_pos);
762                     flv->validate_count = 0;
763                 }
764             } else if (pos > validate_pos) {
765                 clear_index_entries(s, validate_pos);
766                 flv->validate_count = 0;
767             }
768         }
769
770         if (size == 0)
771             continue;
772
773         next = size + avio_tell(s->pb);
774
775         if (type == FLV_TAG_TYPE_AUDIO) {
776             is_audio = 1;
777             flags    = avio_r8(s->pb);
778             size--;
779         } else if (type == FLV_TAG_TYPE_VIDEO) {
780             is_audio = 0;
781             flags    = avio_r8(s->pb);
782             size--;
783             if ((flags & 0xf0) == 0x50) /* video info / command frame */
784                 goto skip;
785         } else {
786             if (type == FLV_TAG_TYPE_META && size > 13 + 1 + 4)
787                 if (flv_read_metabody(s, next) > 0) {
788                     return flv_data_packet(s, pkt, dts, next);
789                 } else /* skip packet */
790                     av_log(s, AV_LOG_DEBUG,
791                            "Skipping flv packet: type %d, size %d, flags %d.\n",
792                            type, size, flags);
793
794 skip:
795             avio_seek(s->pb, next, SEEK_SET);
796             continue;
797         }
798
799         /* skip empty data packets */
800         if (!size)
801             continue;
802
803         /* now find stream */
804         for (i = 0; i < s->nb_streams; i++) {
805             st = s->streams[i];
806             if (is_audio && st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
807                 if (flv_same_audio_codec(st->codecpar, flags))
808                     break;
809             } else if (!is_audio &&
810                        st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
811                 if (flv_same_video_codec(st->codecpar, flags))
812                     break;
813             }
814         }
815         if (i == s->nb_streams) {
816             st = create_stream(s, is_audio ? AVMEDIA_TYPE_AUDIO
817                                            : AVMEDIA_TYPE_VIDEO);
818             if (!st)
819                 return AVERROR(ENOMEM);
820         }
821         av_log(s, AV_LOG_TRACE, "%d %X %d \n", is_audio, flags, st->discard);
822
823         if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
824             is_audio)
825             av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
826
827         if ((st->discard >= AVDISCARD_NONKEY &&
828              !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio)) ||
829             (st->discard >= AVDISCARD_BIDIR &&
830              ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio)) ||
831             st->discard >= AVDISCARD_ALL) {
832             avio_seek(s->pb, next, SEEK_SET);
833             continue;
834         }
835         break;
836     }
837
838     // if not streamed and no duration from metadata then seek to end to find
839     // the duration from the timestamps
840     if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
841         (!s->duration || s->duration == AV_NOPTS_VALUE) &&
842         !flv->searched_for_end) {
843         int size;
844         const int64_t pos   = avio_tell(s->pb);
845         // Read the last 4 bytes of the file, this should be the size of the
846         // previous FLV tag. Use the timestamp of its payload as duration.
847         const int64_t fsize = avio_size(s->pb);
848         avio_seek(s->pb, fsize - 4, SEEK_SET);
849         size = avio_rb32(s->pb);
850         if (size > 0 && size < fsize) {
851             // Seek to the start of the last FLV tag at position (fsize - 4 - size)
852             // but skip the byte indicating the type.
853             avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
854             if (size == avio_rb24(s->pb) + 11) {
855                 uint32_t ts = avio_rb24(s->pb);
856                 ts         |= avio_r8(s->pb) << 24;
857                 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
858             }
859         }
860         avio_seek(s->pb, pos, SEEK_SET);
861         flv->searched_for_end = 1;
862     }
863
864     if (is_audio) {
865         int bits_per_coded_sample;
866         channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
867         sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
868                                 FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
869         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
870         if (!st->codecpar->channels || !st->codecpar->sample_rate ||
871             !st->codecpar->bits_per_coded_sample) {
872             st->codecpar->channels              = channels;
873             st->codecpar->channel_layout        = channels == 1
874                                                ? AV_CH_LAYOUT_MONO
875                                                : AV_CH_LAYOUT_STEREO;
876             st->codecpar->sample_rate           = sample_rate;
877             st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
878         }
879         if (!st->codecpar->codec_id) {
880             flv_set_audio_codec(s, st, st->codecpar,
881                                 flags & FLV_AUDIO_CODECID_MASK);
882             flv->last_sample_rate =
883             sample_rate           = st->codecpar->sample_rate;
884             flv->last_channels    =
885             channels              = st->codecpar->channels;
886         } else {
887             AVCodecParameters *par = avcodec_parameters_alloc();
888             if (!par) {
889                 ret = AVERROR(ENOMEM);
890                 goto leave;
891             }
892             par->sample_rate = sample_rate;
893             par->bits_per_coded_sample = bits_per_coded_sample;
894             flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
895             sample_rate = par->sample_rate;
896             avcodec_parameters_free(&par);
897         }
898     } else {
899         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
900     }
901
902     if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
903         st->codecpar->codec_id == AV_CODEC_ID_H264) {
904         int type = avio_r8(s->pb);
905         size--;
906         if (st->codecpar->codec_id == AV_CODEC_ID_H264) {
907             // sign extension
908             int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
909             pts = dts + cts;
910             if (cts < 0 && !flv->wrong_dts) { // dts might be wrong
911                 flv->wrong_dts = 1;
912                 av_log(s, AV_LOG_WARNING,
913                        "Negative cts, previous timestamps might be wrong.\n");
914             }
915         }
916         if (type == 0) {
917             if (st->codecpar->extradata) {
918                 if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
919                     return ret;
920                 ret = AVERROR(EAGAIN);
921                 goto leave;
922             }
923             if ((ret = flv_get_extradata(s, st, size)) < 0)
924                 return ret;
925             if (st->codecpar->codec_id == AV_CODEC_ID_AAC) {
926                 MPEG4AudioConfig cfg;
927
928                 /* Workaround for buggy Omnia A/XE encoder */
929                 AVDictionaryEntry *t = av_dict_get(s->metadata, "Encoder", NULL, 0);
930                 if (t && !strcmp(t->value, "Omnia A/XE"))
931                     st->codecpar->extradata_size = 2;
932
933                 avpriv_mpeg4audio_get_config(&cfg, st->codecpar->extradata,
934                                              st->codecpar->extradata_size * 8, 1);
935                 st->codecpar->channels       = cfg.channels;
936                 st->codecpar->channel_layout = 0;
937                 if (cfg.ext_sample_rate)
938                     st->codecpar->sample_rate = cfg.ext_sample_rate;
939                 else
940                     st->codecpar->sample_rate = cfg.sample_rate;
941                 av_log(s, AV_LOG_TRACE, "mp4a config channels %d sample rate %d\n",
942                        st->codecpar->channels, st->codecpar->sample_rate);
943             }
944
945             ret = AVERROR(EAGAIN);
946             goto leave;
947         }
948     }
949
950     /* skip empty data packets */
951     if (!size) {
952         ret = AVERROR(EAGAIN);
953         goto leave;
954     }
955
956     ret = av_get_packet(s->pb, pkt, size);
957     if (ret < 0)
958         return AVERROR(EIO);
959     /* note: we need to modify the packet size here to handle the last
960      * packet */
961     pkt->size         = ret;
962     pkt->dts          = dts;
963     pkt->pts          = pts == AV_NOPTS_VALUE ? dts : pts;
964     pkt->stream_index = st->index;
965     if (flv->new_extradata[is_audio]) {
966         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
967                                                 flv->new_extradata_size[is_audio]);
968         if (side) {
969             memcpy(side, flv->new_extradata[is_audio],
970                    flv->new_extradata_size[is_audio]);
971             av_freep(&flv->new_extradata[is_audio]);
972             flv->new_extradata_size[is_audio] = 0;
973         }
974     }
975     if (is_audio && (sample_rate != flv->last_sample_rate ||
976                      channels    != flv->last_channels)) {
977         flv->last_sample_rate = sample_rate;
978         flv->last_channels    = channels;
979         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
980     }
981
982     if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
983         pkt->flags |= AV_PKT_FLAG_KEY;
984
985 leave:
986     avio_skip(s->pb, 4);
987     return ret;
988 }
989
990 static int flv_read_seek(AVFormatContext *s, int stream_index,
991                          int64_t ts, int flags)
992 {
993     FLVContext *flv = s->priv_data;
994     flv->validate_count = 0;
995     return avio_seek_time(s->pb, stream_index, ts, flags);
996 }
997
998 #define OFFSET(x) offsetof(FLVContext, x)
999 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1000 static const AVOption options[] = {
1001     { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1002     { NULL }
1003 };
1004
1005 static const AVClass class = {
1006     .class_name = "flvdec",
1007     .item_name  = av_default_item_name,
1008     .option     = options,
1009     .version    = LIBAVUTIL_VERSION_INT,
1010 };
1011
1012 AVInputFormat ff_flv_demuxer = {
1013     .name           = "flv",
1014     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1015     .priv_data_size = sizeof(FLVContext),
1016     .read_probe     = flv_probe,
1017     .read_header    = flv_read_header,
1018     .read_packet    = flv_read_packet,
1019     .read_seek      = flv_read_seek,
1020     .read_close     = flv_read_close,
1021     .extensions     = "flv",
1022     .priv_class     = &class,
1023 };