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