]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavformat / flvdec.c
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 4bits: difference between encoded width and visible width
8  *  - lower 4bits: 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/dict.h"
29 #include "libavutil/intfloat.h"
30 #include "libavutil/mathematics.h"
31 #include "libavcodec/bytestream.h"
32 #include "libavcodec/mpeg4audio.h"
33 #include "avformat.h"
34 #include "internal.h"
35 #include "avio_internal.h"
36 #include "flv.h"
37
38 #define VALIDATE_INDEX_TS_THRESH 2500
39
40 typedef struct {
41     int wrong_dts; ///< wrong dts due to negative cts
42     uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
43     int      new_extradata_size[FLV_STREAM_TYPE_NB];
44     int      last_sample_rate;
45     int      last_channels;
46     struct {
47         int64_t dts;
48         int64_t pos;
49     } validate_index[2];
50     int validate_next;
51     int validate_count;
52 } FLVContext;
53
54 static int flv_probe(AVProbeData *p)
55 {
56     const uint8_t *d;
57
58     d = p->buf;
59     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
60         return AVPROBE_SCORE_MAX;
61     }
62     return 0;
63 }
64
65 static AVStream *create_stream(AVFormatContext *s, int tag, int codec_type){
66     AVStream *st = avformat_new_stream(s, NULL);
67     if (!st)
68         return NULL;
69     st->id = tag;
70     st->codec->codec_type = codec_type;
71     if(s->nb_streams>=3 ||(   s->nb_streams==2
72                            && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_DATA
73                            && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_DATA))
74         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
75
76     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
77     return st;
78 }
79
80 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid) {
81     switch(flv_codecid) {
82         //no distinction between S16 and S8 PCM codec flags
83         case FLV_CODECID_PCM:
84             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 :
85 #if HAVE_BIGENDIAN
86                                 CODEC_ID_PCM_S16BE;
87 #else
88                                 CODEC_ID_PCM_S16LE;
89 #endif
90             break;
91         case FLV_CODECID_PCM_LE:
92             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 : CODEC_ID_PCM_S16LE; break;
93         case FLV_CODECID_AAC  : acodec->codec_id = CODEC_ID_AAC;                                    break;
94         case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF;                              break;
95         case FLV_CODECID_SPEEX:
96             acodec->codec_id = CODEC_ID_SPEEX;
97             acodec->sample_rate = 16000;
98             break;
99         case FLV_CODECID_MP3  : acodec->codec_id = CODEC_ID_MP3      ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
100         case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
101             acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
102             acodec->codec_id = CODEC_ID_NELLYMOSER;
103             break;
104         case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
105             acodec->sample_rate = 16000;
106             acodec->codec_id = CODEC_ID_NELLYMOSER;
107             break;
108         case FLV_CODECID_NELLYMOSER:
109             acodec->codec_id = CODEC_ID_NELLYMOSER;
110             break;
111         default:
112             av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
113             acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
114     }
115 }
116
117 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
118     AVCodecContext *vcodec = vstream->codec;
119     switch(flv_codecid) {
120         case FLV_CODECID_H263  : vcodec->codec_id = CODEC_ID_FLV1   ; break;
121         case FLV_CODECID_REALH263: vcodec->codec_id = CODEC_ID_H263 ; break; // Really mean it this time
122         case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
123         case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
124         case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;
125         case FLV_CODECID_VP6A  :
126             if(flv_codecid == FLV_CODECID_VP6A)
127                 vcodec->codec_id = CODEC_ID_VP6A;
128             if(vcodec->extradata_size != 1) {
129                 vcodec->extradata_size = 1;
130                 vcodec->extradata = av_malloc(1 + FF_INPUT_BUFFER_PADDING_SIZE);
131             }
132             vcodec->extradata[0] = avio_r8(s->pb);
133             return 1; // 1 byte body size adjustment for flv_read_packet()
134         case FLV_CODECID_H264:
135             vcodec->codec_id = CODEC_ID_H264;
136             return 3; // not 4, reading packet type will consume one byte
137         case FLV_CODECID_MPEG4:
138             vcodec->codec_id = CODEC_ID_MPEG4;
139             return 3;
140         default:
141             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
142             vcodec->codec_tag = flv_codecid;
143     }
144
145     return 0;
146 }
147
148 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
149     int length = avio_rb16(ioc);
150     if(length >= buffsize) {
151         avio_skip(ioc, length);
152         return -1;
153     }
154
155     avio_read(ioc, buffer, length);
156
157     buffer[length] = '\0';
158
159     return length;
160 }
161
162 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
163     FLVContext *flv = s->priv_data;
164     unsigned int timeslen = 0, fileposlen = 0, i;
165     char str_val[256];
166     int64_t *times = NULL;
167     int64_t *filepositions = NULL;
168     int ret = AVERROR(ENOSYS);
169     int64_t initial_pos = avio_tell(ioc);
170
171     if(vstream->nb_index_entries>0){
172         av_log(s, AV_LOG_WARNING, "Skiping duplicate index\n");
173         return 0;
174     }
175
176     if (s->flags & AVFMT_FLAG_IGNIDX)
177         return 0;
178
179     while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
180         int64_t** current_array;
181         unsigned int arraylen;
182
183         // Expect array object in context
184         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
185             break;
186
187         arraylen = avio_rb32(ioc);
188         if(arraylen>>28)
189             break;
190
191         if       (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times){
192             current_array= &times;
193             timeslen= arraylen;
194         }else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions){
195             current_array= &filepositions;
196             fileposlen= arraylen;
197         }else // unexpected metatag inside keyframes, will not use such metadata for indexing
198             break;
199
200         if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
201             ret = AVERROR(ENOMEM);
202             goto finish;
203         }
204
205         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
206             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
207                 goto invalid;
208             current_array[0][i] = av_int2double(avio_rb64(ioc));
209         }
210         if (times && filepositions) {
211             // All done, exiting at a position allowing amf_parse_object
212             // to finish parsing the object
213             ret = 0;
214             break;
215         }
216     }
217
218     if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
219         for (i = 0; i < fileposlen; i++) {
220             av_add_index_entry(vstream, filepositions[i], times[i]*1000,
221                                0, 0, AVINDEX_KEYFRAME);
222             if (i < 2) {
223                 flv->validate_index[i].pos = filepositions[i];
224                 flv->validate_index[i].dts = times[i] * 1000;
225                 flv->validate_count = i + 1;
226             }
227         }
228     } else {
229 invalid:
230         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
231     }
232
233 finish:
234     av_freep(&times);
235     av_freep(&filepositions);
236     avio_seek(ioc, initial_pos, SEEK_SET);
237     return ret;
238 }
239
240 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
241     AVCodecContext *acodec, *vcodec;
242     AVIOContext *ioc;
243     AMFDataType amf_type;
244     char str_val[256];
245     double num_val;
246
247     num_val = 0;
248     ioc = s->pb;
249
250     amf_type = avio_r8(ioc);
251
252     switch(amf_type) {
253         case AMF_DATA_TYPE_NUMBER:
254             num_val = av_int2double(avio_rb64(ioc)); break;
255         case AMF_DATA_TYPE_BOOL:
256             num_val = avio_r8(ioc); break;
257         case AMF_DATA_TYPE_STRING:
258             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
259                 return -1;
260             break;
261         case AMF_DATA_TYPE_OBJECT:
262             if ((vstream || astream) && ioc->seekable && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
263                 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
264                                           max_pos) < 0)
265                     av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
266
267             while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
268                 if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
269                     return -1; //if we couldn't skip, bomb out.
270             }
271             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
272                 return -1;
273             break;
274         case AMF_DATA_TYPE_NULL:
275         case AMF_DATA_TYPE_UNDEFINED:
276         case AMF_DATA_TYPE_UNSUPPORTED:
277             break; //these take up no additional space
278         case AMF_DATA_TYPE_MIXEDARRAY:
279             avio_skip(ioc, 4); //skip 32-bit max array index
280             while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
281                 //this is the only case in which we would want a nested parse to not skip over the object
282                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
283                     return -1;
284             }
285             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
286                 return -1;
287             break;
288         case AMF_DATA_TYPE_ARRAY: {
289             unsigned int arraylen, i;
290
291             arraylen = avio_rb32(ioc);
292             for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
293                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
294                     return -1; //if we couldn't skip, bomb out.
295             }
296         }
297             break;
298         case AMF_DATA_TYPE_DATE:
299             avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
300             break;
301         default: //unsupported type, we couldn't skip
302             return -1;
303     }
304
305     if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
306         acodec = astream ? astream->codec : NULL;
307         vcodec = vstream ? vstream->codec : NULL;
308
309         if (amf_type == AMF_DATA_TYPE_NUMBER) {
310             if (!strcmp(key, "duration"))
311                 s->duration = num_val * AV_TIME_BASE;
312             else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
313                 vcodec->bit_rate = num_val * 1024.0;
314             else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
315                 acodec->bit_rate = num_val * 1024.0;
316             else if (!strcmp(key, "datastream")) {
317                 AVStream *st = create_stream(s, 2, AVMEDIA_TYPE_DATA);
318                 if (!st)
319                     return AVERROR(ENOMEM);
320                 st->codec->codec_id = CODEC_ID_TEXT;
321             }
322         }
323
324         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
325            ((!acodec && !strcmp(key, "audiocodecid")) ||
326             (!vcodec && !strcmp(key, "videocodecid"))))
327                 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
328
329         if (!strcmp(key, "duration")        ||
330             !strcmp(key, "filesize")        ||
331             !strcmp(key, "width")           ||
332             !strcmp(key, "height")          ||
333             !strcmp(key, "videodatarate")   ||
334             !strcmp(key, "framerate")       ||
335             !strcmp(key, "videocodecid")    ||
336             !strcmp(key, "audiodatarate")   ||
337             !strcmp(key, "audiosamplerate") ||
338             !strcmp(key, "audiosamplesize") ||
339             !strcmp(key, "stereo")          ||
340             !strcmp(key, "audiocodecid"))
341             return 0;
342
343         if(amf_type == AMF_DATA_TYPE_BOOL) {
344             av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
345             av_dict_set(&s->metadata, key, str_val, 0);
346         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
347             snprintf(str_val, sizeof(str_val), "%.f", num_val);
348             av_dict_set(&s->metadata, key, str_val, 0);
349         } else if (amf_type == AMF_DATA_TYPE_STRING)
350             av_dict_set(&s->metadata, key, str_val, 0);
351     }
352
353     return 0;
354 }
355
356 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
357     AMFDataType type;
358     AVStream *stream, *astream, *vstream, *dstream;
359     AVIOContext *ioc;
360     int i;
361     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
362
363     vstream = astream = dstream = NULL;
364     ioc = s->pb;
365
366     //first object needs to be "onMetaData" string
367     type = avio_r8(ioc);
368     if (type != AMF_DATA_TYPE_STRING ||
369         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
370         return -1;
371
372     if (!strcmp(buffer, "onTextData"))
373         return 1;
374
375     if (strcmp(buffer, "onMetaData"))
376         return -1;
377
378     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
379     for(i = 0; i < s->nb_streams; i++) {
380         stream = s->streams[i];
381         if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
382         else if(stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
383         else if(stream->codec->codec_type == AVMEDIA_TYPE_DATA) dstream = stream;
384     }
385
386     //parse the second object (we want a mixed array)
387     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
388         return -1;
389
390     return 0;
391 }
392
393 static int flv_read_header(AVFormatContext *s)
394 {
395     int offset, flags;
396
397     avio_skip(s->pb, 4);
398     flags = avio_r8(s->pb);
399     /* old flvtool cleared this field */
400     /* FIXME: better fix needed */
401     if (!flags) {
402         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
403         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
404     }
405         s->ctx_flags |= AVFMTCTX_NOHEADER;
406
407     if(flags & FLV_HEADER_FLAG_HASVIDEO){
408         if(!create_stream(s, 0, AVMEDIA_TYPE_VIDEO))
409             return AVERROR(ENOMEM);
410     }
411     if(flags & FLV_HEADER_FLAG_HASAUDIO){
412         if(!create_stream(s, 1, AVMEDIA_TYPE_AUDIO))
413             return AVERROR(ENOMEM);
414     }
415     // Flag doesn't indicate whether or not there is script-data present. Must
416     // create that stream if it's encountered.
417
418     offset = avio_rb32(s->pb);
419     avio_seek(s->pb, offset, SEEK_SET);
420     avio_skip(s->pb, 4);
421
422     s->start_time = 0;
423
424     return 0;
425 }
426
427 static int flv_read_close(AVFormatContext *s)
428 {
429     int i;
430     FLVContext *flv = s->priv_data;
431     for(i=0; i<FLV_STREAM_TYPE_NB; i++)
432         av_freep(&flv->new_extradata[i]);
433     return 0;
434 }
435
436 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
437 {
438     av_free(st->codec->extradata);
439     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
440     if (!st->codec->extradata)
441         return AVERROR(ENOMEM);
442     st->codec->extradata_size = size;
443     avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
444     return 0;
445 }
446
447 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
448                                int size)
449 {
450     av_free(flv->new_extradata[stream]);
451     flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
452     if (!flv->new_extradata[stream])
453         return AVERROR(ENOMEM);
454     flv->new_extradata_size[stream] = size;
455     avio_read(pb, flv->new_extradata[stream], size);
456     return 0;
457 }
458
459 static void clear_index_entries(AVFormatContext *s, int64_t pos)
460 {
461     int i, j, out;
462     av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
463     for (i = 0; i < s->nb_streams; i++) {
464         AVStream *st = s->streams[i];
465         /* Remove all index entries that point to >= pos */
466         out = 0;
467         for (j = 0; j < st->nb_index_entries; j++) {
468             if (st->index_entries[j].pos < pos)
469                 st->index_entries[out++] = st->index_entries[j];
470         }
471         st->nb_index_entries = out;
472     }
473 }
474
475
476 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
477                            int64_t dts, int64_t next)
478 {
479     int ret = AVERROR_INVALIDDATA, i;
480     AVIOContext *pb = s->pb;
481     AVStream *st = NULL;
482     AMFDataType type;
483     char buf[20];
484     int length;
485
486     type = avio_r8(pb);
487     if (type == AMF_DATA_TYPE_MIXEDARRAY)
488         avio_seek(pb, 4, SEEK_CUR);
489     else if (type != AMF_DATA_TYPE_OBJECT)
490         goto out;
491
492     amf_get_string(pb, buf, sizeof(buf));
493     if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
494         goto out;
495
496     amf_get_string(pb, buf, sizeof(buf));
497     //FIXME parse it as codec_id
498     amf_get_string(pb, buf, sizeof(buf));
499     if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
500         goto out;
501
502     length = avio_rb16(pb);
503     ret = av_get_packet(s->pb, pkt, length);
504     if (ret < 0) {
505         ret = AVERROR(EIO);
506         goto out;
507     }
508
509     for (i = 0; i < s->nb_streams; i++) {
510         st = s->streams[i];
511         if (st->id == 2)
512             break;
513     }
514
515     if (i == s->nb_streams) {
516         st = create_stream(s, 2, AVMEDIA_TYPE_DATA);
517         if (!st)
518             goto out;
519         st->codec->codec_id = CODEC_ID_TEXT;
520     }
521
522     pkt->dts  = dts;
523     pkt->pts  = dts;
524     pkt->size = ret;
525
526     pkt->stream_index = st->index;
527     pkt->flags |= AV_PKT_FLAG_KEY;
528
529     avio_seek(s->pb, next + 4, SEEK_SET);
530 out:
531     return ret;
532 }
533
534 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
535 {
536     FLVContext *flv = s->priv_data;
537     int ret, i, type, size, flags;
538     int stream_type=-1;
539     int64_t next, pos;
540     int64_t dts, pts = AV_NOPTS_VALUE;
541     int av_uninit(channels);
542     int av_uninit(sample_rate);
543     AVStream *st = NULL;
544
545  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
546     pos = avio_tell(s->pb);
547     type = avio_r8(s->pb);
548     size = avio_rb24(s->pb);
549     dts = avio_rb24(s->pb);
550     dts |= avio_r8(s->pb) << 24;
551     av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
552     if (url_feof(s->pb))
553         return AVERROR_EOF;
554     avio_skip(s->pb, 3); /* stream id, always 0 */
555     flags = 0;
556
557     if (flv->validate_next < flv->validate_count) {
558         int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
559         if (pos == validate_pos) {
560             if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
561                 VALIDATE_INDEX_TS_THRESH) {
562                 flv->validate_next++;
563             } else {
564                 clear_index_entries(s, validate_pos);
565                 flv->validate_count = 0;
566             }
567         } else if (pos > validate_pos) {
568             clear_index_entries(s, validate_pos);
569             flv->validate_count = 0;
570         }
571     }
572
573     if(size == 0)
574         continue;
575
576     next= size + avio_tell(s->pb);
577
578     if (type == FLV_TAG_TYPE_AUDIO) {
579         stream_type=FLV_STREAM_TYPE_AUDIO;
580         flags = avio_r8(s->pb);
581         size--;
582     } else if (type == FLV_TAG_TYPE_VIDEO) {
583         stream_type=FLV_STREAM_TYPE_VIDEO;
584         flags = avio_r8(s->pb);
585         size--;
586         if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
587             goto skip;
588     } else if (type == FLV_TAG_TYPE_META) {
589         if (size > 13+1+4 && dts == 0) { // Header-type metadata stuff
590             flv_read_metabody(s, next);
591             goto skip;
592         } else if (dts != 0) { // Script-data "special" metadata frames - don't skip
593             stream_type=FLV_STREAM_TYPE_DATA;
594         } else {
595             goto skip;
596         }
597     } else {
598         av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
599     skip:
600         avio_seek(s->pb, next, SEEK_SET);
601         continue;
602     }
603
604     /* skip empty data packets */
605     if (!size)
606         continue;
607
608     /* now find stream */
609     for(i=0;i<s->nb_streams;i++) {
610         st = s->streams[i];
611         if (st->id == stream_type)
612             break;
613     }
614     if(i == s->nb_streams){
615         av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
616         st = create_stream(s, stream_type,
617              (int[]){AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA}[stream_type]);
618     }
619     av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
620     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
621        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
622        || st->discard >= AVDISCARD_ALL
623        ){
624         avio_seek(s->pb, next, SEEK_SET);
625         continue;
626     }
627     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
628         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
629     break;
630  }
631
632     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
633     if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
634         int size;
635         const int64_t pos= avio_tell(s->pb);
636         const int64_t fsize= avio_size(s->pb);
637         avio_seek(s->pb, fsize-4, SEEK_SET);
638         size= avio_rb32(s->pb);
639         avio_seek(s->pb, fsize-3-size, SEEK_SET);
640         if(size == avio_rb24(s->pb) + 11){
641             uint32_t ts = avio_rb24(s->pb);
642             ts |= avio_r8(s->pb) << 24;
643             s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
644         }
645         avio_seek(s->pb, pos, SEEK_SET);
646     }
647
648     if(stream_type == FLV_STREAM_TYPE_AUDIO){
649         int bits_per_coded_sample;
650         channels    = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
651         sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
652         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
653         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
654             st->codec->channels              = channels;
655             st->codec->sample_rate           = sample_rate;
656             st->codec->bits_per_coded_sample = bits_per_coded_sample;
657         }
658         if(!st->codec->codec_id){
659             flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
660             flv->last_sample_rate = sample_rate = st->codec->sample_rate;
661             flv->last_channels    = channels    = st->codec->channels;
662         } else {
663             AVCodecContext ctx;
664             ctx.sample_rate = sample_rate;
665             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
666             sample_rate = ctx.sample_rate;
667         }
668     } else if(stream_type == FLV_STREAM_TYPE_VIDEO) {
669         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
670     }
671
672     if (st->codec->codec_id == CODEC_ID_AAC ||
673         st->codec->codec_id == CODEC_ID_H264 ||
674         st->codec->codec_id == CODEC_ID_MPEG4) {
675         int type = avio_r8(s->pb);
676         size--;
677         if (st->codec->codec_id == CODEC_ID_H264 || st->codec->codec_id == CODEC_ID_MPEG4) {
678             int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
679             pts = dts + cts;
680             if (cts < 0) { // dts are wrong
681                 flv->wrong_dts = 1;
682                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
683             }
684             if (flv->wrong_dts)
685                 dts = AV_NOPTS_VALUE;
686         }
687         if (type == 0 && (!st->codec->extradata || st->codec->codec_id == CODEC_ID_AAC)) {
688             if (st->codec->extradata) {
689                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
690                     return ret;
691                 ret = AVERROR(EAGAIN);
692                 goto leave;
693             }
694             if ((ret = flv_get_extradata(s, st, size)) < 0)
695                 return ret;
696             if (st->codec->codec_id == CODEC_ID_AAC) {
697                 MPEG4AudioConfig cfg;
698                 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
699                                              st->codec->extradata_size * 8, 1) >= 0) {
700                 st->codec->channels = cfg.channels;
701                 if (cfg.ext_sample_rate)
702                     st->codec->sample_rate = cfg.ext_sample_rate;
703                 else
704                     st->codec->sample_rate = cfg.sample_rate;
705                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
706                         st->codec->channels, st->codec->sample_rate);
707                 }
708             }
709
710             ret = AVERROR(EAGAIN);
711             goto leave;
712         }
713     }
714
715     /* skip empty data packets */
716     if (!size) {
717         ret = AVERROR(EAGAIN);
718         goto leave;
719     }
720
721     ret= av_get_packet(s->pb, pkt, size);
722     if (ret < 0)
723         return ret;
724     pkt->dts = dts;
725     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
726     pkt->stream_index = st->index;
727     if (flv->new_extradata[stream_type]) {
728         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
729                                                 flv->new_extradata_size[stream_type]);
730         if (side) {
731             memcpy(side, flv->new_extradata[stream_type],
732                    flv->new_extradata_size[stream_type]);
733             av_freep(&flv->new_extradata[stream_type]);
734             flv->new_extradata_size[stream_type] = 0;
735         }
736     }
737     if (stream_type == FLV_STREAM_TYPE_AUDIO && (sample_rate != flv->last_sample_rate ||
738                      channels != flv->last_channels)) {
739         flv->last_sample_rate = sample_rate;
740         flv->last_channels    = channels;
741         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
742     }
743
744     if (    stream_type == FLV_STREAM_TYPE_AUDIO ||
745             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
746             stream_type == FLV_STREAM_TYPE_DATA)
747         pkt->flags |= AV_PKT_FLAG_KEY;
748
749 leave:
750     avio_skip(s->pb, 4);
751     return ret;
752 }
753
754 static int flv_read_seek(AVFormatContext *s, int stream_index,
755     int64_t ts, int flags)
756 {
757     FLVContext *flv = s->priv_data;
758     flv->validate_count = 0;
759     return avio_seek_time(s->pb, stream_index, ts, flags);
760 }
761
762 AVInputFormat ff_flv_demuxer = {
763     .name           = "flv",
764     .long_name      = NULL_IF_CONFIG_SMALL("FLV format"),
765     .priv_data_size = sizeof(FLVContext),
766     .read_probe     = flv_probe,
767     .read_header    = flv_read_header,
768     .read_packet    = flv_read_packet,
769     .read_seek      = flv_read_seek,
770     .read_close     = flv_read_close,
771     .extensions     = "flv",
772 };