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