]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
lavfi: allow audio filters to request a given number of samples.
[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 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 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/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 KEYFRAMES_TAG            "keyframes"
39 #define KEYFRAMES_TIMESTAMP_TAG  "times"
40 #define KEYFRAMES_BYTEOFFSET_TAG "filepositions"
41
42 #define VALIDATE_INDEX_TS_THRESH 2500
43
44 typedef struct {
45     int wrong_dts; ///< wrong dts due to negative cts
46     uint8_t *new_extradata[2];
47     int      new_extradata_size[2];
48     int      last_sample_rate;
49     int      last_channels;
50     struct {
51         int64_t dts;
52         int64_t pos;
53     } validate_index[2];
54     int validate_next;
55     int validate_count;
56 } FLVContext;
57
58 static int flv_probe(AVProbeData *p)
59 {
60     const uint8_t *d;
61
62     d = p->buf;
63     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
64         return AVPROBE_SCORE_MAX;
65     }
66     return 0;
67 }
68
69 static AVStream *create_stream(AVFormatContext *s, int tag, int codec_type)
70 {
71     AVStream *st = avformat_new_stream(s, NULL);
72     if (!st)
73         return NULL;
74     st->id = tag;
75     st->codec->codec_type = codec_type;
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_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
122         case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
123         case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;
124         case FLV_CODECID_VP6A  :
125             if(flv_codecid == FLV_CODECID_VP6A)
126                 vcodec->codec_id = CODEC_ID_VP6A;
127             if(vcodec->extradata_size != 1) {
128                 vcodec->extradata_size = 1;
129                 vcodec->extradata = av_malloc(1);
130             }
131             vcodec->extradata[0] = avio_r8(s->pb);
132             return 1; // 1 byte body size adjustment for flv_read_packet()
133         case FLV_CODECID_H264:
134             vcodec->codec_id = CODEC_ID_H264;
135             return 3; // not 4, reading packet type will consume one byte
136         default:
137             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
138             vcodec->codec_tag = flv_codecid;
139     }
140
141     return 0;
142 }
143
144 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
145     int length = avio_rb16(ioc);
146     if(length >= buffsize) {
147         avio_skip(ioc, length);
148         return -1;
149     }
150
151     avio_read(ioc, buffer, length);
152
153     buffer[length] = '\0';
154
155     return length;
156 }
157
158 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
159     FLVContext *flv = s->priv_data;
160     unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
161     double num_val;
162     char str_val[256];
163     int64_t *times = NULL;
164     int64_t *filepositions = NULL;
165     int ret = AVERROR(ENOSYS);
166     int64_t initial_pos = avio_tell(ioc);
167
168     if (s->flags & AVFMT_FLAG_IGNIDX)
169         return 0;
170
171     while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
172         int64_t* current_array;
173
174         // Expect array object in context
175         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
176             break;
177
178         arraylen = avio_rb32(ioc);
179         if (arraylen >> 28)
180             break;
181
182         /*
183          * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata
184          * for indexing
185          */
186         if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
187             if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
188                 ret = AVERROR(ENOMEM);
189                 goto finish;
190             }
191             timeslen = arraylen;
192             current_array = times;
193         } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {
194             if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
195                 ret = AVERROR(ENOMEM);
196                 goto finish;
197             }
198             fileposlen = arraylen;
199             current_array = filepositions;
200         } else // unexpected metatag inside keyframes, will not use such metadata for indexing
201             break;
202
203         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
204             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
205                 goto finish;
206             num_val = av_int2double(avio_rb64(ioc));
207             current_array[i] = num_val;
208         }
209         if (times && filepositions) {
210             // All done, exiting at a position allowing amf_parse_object
211             // to finish parsing the object
212             ret = 0;
213             break;
214         }
215     }
216
217     if (!ret && timeslen == fileposlen) {
218         for (i = 0; i < fileposlen; i++) {
219             av_add_index_entry(vstream, filepositions[i], times[i]*1000,
220                                0, 0, AVINDEX_KEYFRAME);
221             if (i < 2) {
222                 flv->validate_index[i].pos = filepositions[i];
223                 flv->validate_index[i].dts = times[i] * 1000;
224                 flv->validate_count = i + 1;
225             }
226         }
227     } else
228         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
229
230 finish:
231     av_freep(&times);
232     av_freep(&filepositions);
233     // If we got unexpected data, but successfully reset back to
234     // the start pos, the caller can continue parsing
235     if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
236         return 0;
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) && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
263                 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
264                                           max_pos) < 0)
265                     return -1;
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 (!strcmp(key, "duration")        ||
325             !strcmp(key, "filesize")        ||
326             !strcmp(key, "width")           ||
327             !strcmp(key, "height")          ||
328             !strcmp(key, "videodatarate")   ||
329             !strcmp(key, "framerate")       ||
330             !strcmp(key, "videocodecid")    ||
331             !strcmp(key, "audiodatarate")   ||
332             !strcmp(key, "audiosamplerate") ||
333             !strcmp(key, "audiosamplesize") ||
334             !strcmp(key, "stereo")          ||
335             !strcmp(key, "audiocodecid"))
336             return 0;
337
338         if(amf_type == AMF_DATA_TYPE_BOOL) {
339             av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
340             av_dict_set(&s->metadata, key, str_val, 0);
341         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
342             snprintf(str_val, sizeof(str_val), "%.f", num_val);
343             av_dict_set(&s->metadata, key, str_val, 0);
344         } else if (amf_type == AMF_DATA_TYPE_STRING)
345             av_dict_set(&s->metadata, key, str_val, 0);
346     }
347
348     return 0;
349 }
350
351 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
352     AMFDataType type;
353     AVStream *stream, *astream, *vstream;
354     AVIOContext *ioc;
355     int i;
356     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
357
358     astream = NULL;
359     vstream = NULL;
360     ioc = s->pb;
361
362     //first object needs to be "onMetaData" string
363     type = avio_r8(ioc);
364     if (type != AMF_DATA_TYPE_STRING ||
365         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
366         return -1;
367
368     if (!strcmp(buffer, "onTextData"))
369         return 1;
370
371     if (strcmp(buffer, "onMetaData"))
372         return -1;
373
374     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
375     for(i = 0; i < s->nb_streams; i++) {
376         stream = s->streams[i];
377         if     (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
378         else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
379     }
380
381     //parse the second object (we want a mixed array)
382     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
383         return -1;
384
385     return 0;
386 }
387
388 static int flv_read_header(AVFormatContext *s)
389 {
390     int offset, flags;
391
392     avio_skip(s->pb, 4);
393     flags = avio_r8(s->pb);
394     /* old flvtool cleared this field */
395     /* FIXME: better fix needed */
396     if (!flags) {
397         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
398         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
399     }
400
401     if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
402              != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
403         s->ctx_flags |= AVFMTCTX_NOHEADER;
404
405     if(flags & FLV_HEADER_FLAG_HASVIDEO){
406         if(!create_stream(s, 0, AVMEDIA_TYPE_VIDEO))
407             return AVERROR(ENOMEM);
408     }
409     if(flags & FLV_HEADER_FLAG_HASAUDIO){
410         if(!create_stream(s, 1, AVMEDIA_TYPE_AUDIO))
411             return AVERROR(ENOMEM);
412     }
413
414     offset = avio_rb32(s->pb);
415     avio_seek(s->pb, offset, SEEK_SET);
416     avio_skip(s->pb, 4);
417
418     s->start_time = 0;
419
420     return 0;
421 }
422
423 static int flv_read_close(AVFormatContext *s)
424 {
425     FLVContext *flv = s->priv_data;
426     av_freep(&flv->new_extradata[0]);
427     av_freep(&flv->new_extradata[1]);
428     return 0;
429 }
430
431 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
432 {
433     av_free(st->codec->extradata);
434     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
435     if (!st->codec->extradata)
436         return AVERROR(ENOMEM);
437     st->codec->extradata_size = size;
438     avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
439     return 0;
440 }
441
442 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
443                                int size)
444 {
445     av_free(flv->new_extradata[stream]);
446     flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
447     if (!flv->new_extradata[stream])
448         return AVERROR(ENOMEM);
449     flv->new_extradata_size[stream] = size;
450     avio_read(pb, flv->new_extradata[stream], size);
451     return 0;
452 }
453
454 static void clear_index_entries(AVFormatContext *s, int64_t pos)
455 {
456     int i, j, out;
457     av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
458     for (i = 0; i < s->nb_streams; i++) {
459         AVStream *st = s->streams[i];
460         /* Remove all index entries that point to >= pos */
461         out = 0;
462         for (j = 0; j < st->nb_index_entries; j++) {
463             if (st->index_entries[j].pos < pos)
464                 st->index_entries[out++] = st->index_entries[j];
465         }
466         st->nb_index_entries = out;
467     }
468 }
469
470
471 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
472                            int64_t dts, int64_t next)
473 {
474     int ret = AVERROR_INVALIDDATA, i;
475     AVIOContext *pb = s->pb;
476     AVStream *st = NULL;
477     AMFDataType type;
478     char buf[20];
479     int length;
480
481     type = avio_r8(pb);
482     if (type == AMF_DATA_TYPE_MIXEDARRAY)
483         avio_seek(pb, 4, SEEK_CUR);
484     else if (type != AMF_DATA_TYPE_OBJECT)
485         goto out;
486
487     amf_get_string(pb, buf, sizeof(buf));
488     if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
489         goto out;
490
491     amf_get_string(pb, buf, sizeof(buf));
492     //FIXME parse it as codec_id
493     amf_get_string(pb, buf, sizeof(buf));
494     if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
495         goto out;
496
497     length = avio_rb16(pb);
498     ret = av_get_packet(s->pb, pkt, length);
499     if (ret < 0) {
500         ret = AVERROR(EIO);
501         goto out;
502     }
503
504     for (i = 0; i < s->nb_streams; i++) {
505         st = s->streams[i];
506         if (st->id == 2)
507             break;
508     }
509
510     if (i == s->nb_streams) {
511         st = create_stream(s, 2, AVMEDIA_TYPE_DATA);
512         if (!st)
513             goto out;
514         st->codec->codec_id = CODEC_ID_TEXT;
515     }
516
517     pkt->dts  = dts;
518     pkt->pts  = dts;
519     pkt->size = ret;
520
521     pkt->stream_index = st->index;
522     pkt->flags |= AV_PKT_FLAG_KEY;
523
524     avio_seek(s->pb, next + 4, SEEK_SET);
525 out:
526     return ret;
527 }
528
529 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
530 {
531     FLVContext *flv = s->priv_data;
532     int ret, i, type, size, flags, is_audio;
533     int64_t next, pos;
534     int64_t dts, pts = AV_NOPTS_VALUE;
535     int sample_rate = 0, channels = 0;
536     AVStream *st = NULL;
537
538  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
539     pos = avio_tell(s->pb);
540     type = avio_r8(s->pb);
541     size = avio_rb24(s->pb);
542     dts = avio_rb24(s->pb);
543     dts |= avio_r8(s->pb) << 24;
544     av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
545     if (s->pb->eof_reached)
546         return AVERROR_EOF;
547     avio_skip(s->pb, 3); /* stream id, always 0 */
548     flags = 0;
549
550     if (flv->validate_next < flv->validate_count) {
551         int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
552         if (pos == validate_pos) {
553             if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
554                 VALIDATE_INDEX_TS_THRESH) {
555                 flv->validate_next++;
556             } else {
557                 clear_index_entries(s, validate_pos);
558                 flv->validate_count = 0;
559             }
560         } else if (pos > validate_pos) {
561             clear_index_entries(s, validate_pos);
562             flv->validate_count = 0;
563         }
564     }
565
566     if(size == 0)
567         continue;
568
569     next= size + avio_tell(s->pb);
570
571     if (type == FLV_TAG_TYPE_AUDIO) {
572         is_audio=1;
573         flags = avio_r8(s->pb);
574         size--;
575     } else if (type == FLV_TAG_TYPE_VIDEO) {
576         is_audio=0;
577         flags = avio_r8(s->pb);
578         size--;
579         if ((flags & 0xf0) == 0x50) /* video info / command frame */
580             goto skip;
581     } else {
582         if (type == FLV_TAG_TYPE_META && size > 13+1+4)
583             if (flv_read_metabody(s, next) > 0) {
584                 return flv_data_packet(s, pkt, dts, next);
585             }
586         else /* skip packet */
587             av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
588     skip:
589         avio_seek(s->pb, next, SEEK_SET);
590         continue;
591     }
592
593     /* skip empty data packets */
594     if (!size)
595         continue;
596
597     /* now find stream */
598     for(i=0;i<s->nb_streams;i++) {
599         st = s->streams[i];
600         if (st->id == is_audio)
601             break;
602     }
603     if(i == s->nb_streams){
604         av_log(s, AV_LOG_ERROR, "invalid stream\n");
605         st = create_stream(s, is_audio,
606              is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO);
607         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
608     }
609     av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
610     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||         is_audio))
611        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
612        || st->discard >= AVDISCARD_ALL
613        ){
614         avio_seek(s->pb, next, SEEK_SET);
615         continue;
616     }
617     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
618         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
619     break;
620  }
621
622     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
623     if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
624         int size;
625         const int64_t pos= avio_tell(s->pb);
626         const int64_t fsize= avio_size(s->pb);
627         avio_seek(s->pb, fsize-4, SEEK_SET);
628         size= avio_rb32(s->pb);
629         avio_seek(s->pb, fsize-3-size, SEEK_SET);
630         if(size == avio_rb24(s->pb) + 11){
631             uint32_t ts = avio_rb24(s->pb);
632             ts |= avio_r8(s->pb) << 24;
633             s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
634         }
635         avio_seek(s->pb, pos, SEEK_SET);
636     }
637
638     if(is_audio){
639         int bits_per_coded_sample;
640         channels    = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
641         sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
642         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
643         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
644             st->codec->channels              = channels;
645             st->codec->sample_rate           = sample_rate;
646             st->codec->bits_per_coded_sample = bits_per_coded_sample;
647         }
648         if(!st->codec->codec_id){
649             flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
650             flv->last_sample_rate = sample_rate = st->codec->sample_rate;
651             flv->last_channels    = channels    = st->codec->channels;
652         } else {
653             AVCodecContext ctx;
654             ctx.sample_rate = sample_rate;
655             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
656             sample_rate = ctx.sample_rate;
657         }
658     }else{
659         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
660     }
661
662     if (st->codec->codec_id == CODEC_ID_AAC ||
663         st->codec->codec_id == CODEC_ID_H264) {
664         int type = avio_r8(s->pb);
665         size--;
666         if (st->codec->codec_id == CODEC_ID_H264) {
667             int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
668             pts = dts + cts;
669             if (cts < 0) { // dts are wrong
670                 flv->wrong_dts = 1;
671                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
672             }
673             if (flv->wrong_dts)
674                 dts = AV_NOPTS_VALUE;
675         }
676         if (type == 0) {
677             if (st->codec->extradata) {
678                 if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
679                     return ret;
680                 ret = AVERROR(EAGAIN);
681                 goto leave;
682             }
683             if ((ret = flv_get_extradata(s, st, size)) < 0)
684                 return ret;
685             if (st->codec->codec_id == CODEC_ID_AAC) {
686                 MPEG4AudioConfig cfg;
687                 avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
688                                              st->codec->extradata_size * 8, 1);
689                 st->codec->channels = cfg.channels;
690                 if (cfg.ext_sample_rate)
691                     st->codec->sample_rate = cfg.ext_sample_rate;
692                 else
693                     st->codec->sample_rate = cfg.sample_rate;
694                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
695                         st->codec->channels, st->codec->sample_rate);
696             }
697
698             ret = AVERROR(EAGAIN);
699             goto leave;
700         }
701     }
702
703     /* skip empty data packets */
704     if (!size) {
705         ret = AVERROR(EAGAIN);
706         goto leave;
707     }
708
709     ret= av_get_packet(s->pb, pkt, size);
710     if (ret < 0) {
711         return AVERROR(EIO);
712     }
713     /* note: we need to modify the packet size here to handle the last
714        packet */
715     pkt->size = ret;
716     pkt->dts = dts;
717     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
718     pkt->stream_index = st->index;
719     if (flv->new_extradata[is_audio]) {
720         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
721                                                 flv->new_extradata_size[is_audio]);
722         if (side) {
723             memcpy(side, flv->new_extradata[is_audio],
724                    flv->new_extradata_size[is_audio]);
725             av_freep(&flv->new_extradata[is_audio]);
726             flv->new_extradata_size[is_audio] = 0;
727         }
728     }
729     if (is_audio && (sample_rate != flv->last_sample_rate ||
730                      channels != flv->last_channels)) {
731         flv->last_sample_rate = sample_rate;
732         flv->last_channels    = channels;
733         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
734     }
735
736     if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
737         pkt->flags |= AV_PKT_FLAG_KEY;
738
739 leave:
740     avio_skip(s->pb, 4);
741     return ret;
742 }
743
744 static int flv_read_seek(AVFormatContext *s, int stream_index,
745     int64_t ts, int flags)
746 {
747     FLVContext *flv = s->priv_data;
748     flv->validate_count = 0;
749     return avio_seek_time(s->pb, stream_index, ts, flags);
750 }
751
752 AVInputFormat ff_flv_demuxer = {
753     .name           = "flv",
754     .long_name      = NULL_IF_CONFIG_SMALL("FLV format"),
755     .priv_data_size = sizeof(FLVContext),
756     .read_probe     = flv_probe,
757     .read_header    = flv_read_header,
758     .read_packet    = flv_read_packet,
759     .read_seek      = flv_read_seek,
760     .read_close     = flv_read_close,
761     .extensions     = "flv",
762 };