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